wdcsx 发表于 2017-4-21 12:35:16

Python嵌入D

  所有的嵌入都研究了一个遍。发现嵌入Python挺好,试试。
  用D写Python的扩展,已经有了pyD,非常好用,效率也很高,http://pyd.dsource.org
  将Python嵌入D,只能使用Raw的C-API了。这里用到了pyD中的Python接口文件
  python.d和python25_digitalmars.lib,并且在本机安装了Python2.5
  1.简单的高层次嵌入:就是执行一个Python的脚本

import python;
void main()
{
Py_Initialize();

PyRun_SimpleString("from time import time,ctime\n"
"print('Today is:',ctime(time()))\n");
Py_Finalize();
}
  2.低层次嵌入:修改了一个C的例子,在D中调用Python函数,并返回值。python脚本和调用写在注释了。

import python;
import std.stdio,std.string,std.c.string;
//call: t sm mw 2 3
/*
'''sm.py'''
def mw(a,b):
print 'Will compute',a,'times',b
c=0
for i in range(0,a):
c=c+b
return c
*/
void main(char[][] argv)
{
PyObject * pName,pModule,pDict,pFunc;
PyObject *pArgs, pValue;
int i,argc;
argc = argv.length;
if (argc < 3) {
printf("Usage: call pythonfile funcname \n");
return 1;
}
printf("args:%d\n",argc);
Py_Initialize();
pName = PyString_FromString( toStringz(argv) );
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != null) {
pFunc = PyObject_GetAttrString(pModule, toStringz(argv));
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
//set args
for (i = 0; i < argc - 3; ++i) {
pValue = PyInt_FromLong(atoi(argv));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
printf("Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
//call function
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs); //release args
if (pValue != null) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue); //release return
}
else {
Py_DECREF(pFunc); //
Py_DECREF(pModule);
PyErr_Print();
printf("Call failed/n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
printf( "Cannot find function \"%s\"\n", argv);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
printf("Failed to load \"%s\"\n", argv);
return 1;
}
Py_Finalize();
return 0;
}

  关键的是在合适的时机释放Python的变量。自己也写了个简单的封装。比较而言,最简单的还是MiniD的嵌入,其次是Lua,Python的比较复杂。Python的好处是类库丰富,几乎要什么有什么。

oversun 发表于 2017-4-21 12:53:55

学习中
页: [1]
查看完整版本: Python嵌入D