下面是 c++ 代码,它将在同一目录中调用我的 python 脚本“rule.py”。
#include <Python.h>
#include <iostream>
using namespace std;
int dou(int a)
{
PyObject *pModule, *pDict, *pFunc, *pArgs, *pRetVal;
if( !Py_IsInitialized() ){
cout<<"Can't initialize"<<endl;
return -1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('.')");
pModule = PyImport_ImportModule("rule");
if( !pModule ){
cout<<"can' import the module "<<endl;
return -1;
}
pDict = PyModule_GetDict(pModule);
if( !pDict ){
cout<<"can't get the dict"<<endl;
return -1;
}
pFunc = PyDict_GetItemString(pDict, "fun");
if( !pFunc || !PyCallable_Check(pFunc) ){
cout<<"can't get the function"<<endl;
return -1;
}
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0,Py_BuildValue("i",a));
pRetVal = PyObject_CallObject(pFunc,pArgs);
int result = PyInt_AsLong(pRetVal);
Py_DECREF(pModule);
Py_DECREF(pDict);
Py_DECREF(pFunc);
Py_DECREF(pArgs);
Py_DECREF(pRetVal);
return result;
}
int main(void)
{
Py_Initialize();
cout<<dou(2)<<endl;
cout<<dou(3)<<endl;
Py_Finalize();
return 0;
}
这是简单的python代码。
def fun(a):
return 2*a
if __name__ == "__main__":
print fun(2)
输出是:
4
can't get the function.
-1
它第一次工作,但第二次调用它时无法获得该功能。也许我错过了什么?