惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
博客园_首页
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
博客园 - 司徒正美
有赞技术团队
有赞技术团队
Engineering at Meta
Engineering at Meta
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog

博客园 - USEGEAR

学习unigui【48】lucksheet表格的显示object 学习使用 处理Python对象和列表【5】 学习使用:创建 Python 可调用的 Delphi 函数【4】 学习使用TPythonDelphiVar组件 数据交换Delphi与Python传值【3】 学习使用 Python4Delphi 是什么【1】 学习unigui【47】扫码安装apk 学习unigui【46】让客户端浏览器可以选下载你的apk 学习unigui【45】UnimDatePicker等按钮汉化崩溃 学习unigui【44】如何和uinHTMLFrame打交道 学习unigui【43】如何和控件打交道 学习unigui【42】UnimDatePicker的使用 学习unigui【41】htmlframe的交互现象 学习unigui【40】加入监控墙-1 头大的内存泄漏 学习unigui【39】单独文件在ms win server 上执行的坑 学习unigui【38】重新认识UUNIGUI--为什么这样快? 站在“架构与性能”层面重新审视 学习unigui【37】nginx的反向代理 ,程序中的重新定向 学习unigui【36】把数据导航放在Unidbgrid脚中 学习unigui【35】dbgrid字段宽度自适应 KingSADA的工业历史数据库的访问
学习使用 数据交换 Delphi 与 Python 传值【2】
USEGEAR · 2026-02-11 · via 博客园 - USEGEAR

Delphi 向 Python 传递变量

procedure TForm1.PassValuesToPython;
var
  PyValue: PPyObject;  // Python 对象指针
begin
  PythonEngine1.LoadDll;
  
  // 【第1段】创建 Python 整数
  PyValue := PythonEngine1.PyLong_FromLong(42);
  
  // 【第2段】将变量注入 Python 全局命名空间
  PythonEngine1.PyDict_SetItemString(
    PythonEngine1.GetMainModule.__dict__, 
    'delphi_number', 
    PyValue
  );
  
  // 【第3段】在 Python 中使用这个变量
  PythonEngine1.ExecString('print(f"Delphi传来的数字: {delphi_number}")');
  
  // 【第4段】释放 Python 对象(重要!防止内存泄漏)
  PythonEngine1.Py_DecRef(PyValue);
end;

关键概念解释:

  • PPyObject - Python 对象的 C 指针,所有 Python 数据都是这种类型

  • PyLong_FromLong() - 将 Delphi 整数转为 Python 整数

  • GetMainModule.__dict__ - Python 的全局变量字典

  • Py_DecRef() - 必须调用,减少引用计数,否则内存泄漏