我正在尝试将 python 程序嵌入到 c++ 代码中。我遇到的问题是使用包含 numpy 导入的 python 脚本。例如,如果我使用以下 c++ 代码
#include <Python.h>
int main(int argc,char *argv[])
{
double
x=2.,
xp=4.,
dt=6.,
y=8,
yp=1,
dz=6;
Py_Initialize();
PyObject* myModuleString = PyString_FromString((char*)"log");
PyObject* myModule = PyImport_Import(myModuleString);
PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"derive");
PyObject* args = PyTuple_Pack( 6,
PyFloat_FromDouble(x),
PyFloat_FromDouble(xp),
PyFloat_FromDouble(dt),
PyFloat_FromDouble(y),
PyFloat_FromDouble(yp),
PyFloat_FromDouble(dz));
PyObject* myResult = PyObject_CallObject(myFunction, args);
PyObject *ts= PyTuple_GetItem(myResult,0);
PyObject *zs= PyTuple_GetItem(myResult,1);
double result_t = PyFloat_AsDouble(ts);
double result_z = PyFloat_AsDouble(zs);
printf("%3f \n %f \n", result_t,result_z);
Py_Finalize();
system("pause");
return 0;
}
使用以下包含该函数的 log.py 脚本derive
def derive(x,xp,dt,y,yp,dz):
return log(abs(x - xp)/dt),exp((y-yp)/dz)
它运行正确,但如果 log.py 包含from numpy import array
,它会失败
from numpy import array
def derive(x,xp,dt,y,yp,dz):
return log(abs(x - xp)/dt),exp((y-yp)/dz)