问题
I'm trying to embed a python program to c++ code. the problem I have is to use python script that contain an numpy import. for example, if i use the following c++ code
#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;
}
with the following log.py script which contain the function derive
def derive(x,xp,dt,y,yp,dz):
return log(abs(x - xp)/dt),exp((y-yp)/dz)
it runs correctly, but if the log.py contain from numpy import array
, it fails
from numpy import array
def derive(x,xp,dt,y,yp,dz):
return log(abs(x - xp)/dt),exp((y-yp)/dz)
回答1:
I think you're linking statically but not retaining all of the symbols, which is required to load dynamic extension modules (i.e. -Xlinker -export-dynamic
). See Linking Requirements, which recommends that you query the correct options from distutils.sysconfig.get_config_var('LINKFORSHARED')
.
BTW, the variadic function Py_BuildValue is a more convenient way to create args
.
回答2:
I know this answer comes late but might help others struggling with the same issue.
The fix that helped me was to make sure that python linked the proper DLL's and libraries, as Python can mix these when multiple versions of Python are installed.
Make sure you run PyRun_SimpleString("import sys")
andPyRun_SimpleString("print sys.path")
, look at the results. If this contains multiple versions of Python, you need to force the right path.
Fire up the Python.exe that you know is the correct version, (that is, where you installed the actual numpy package and link to during compilation) and: import sys
, then print sys.path
. Copy this path to: PyRun_SimpleString("sys.path = [your paths]");
within your C/C++ file. Now the correct path for the DLL's should be forced and importing numpy should not result in a segfault.
来源:https://stackoverflow.com/questions/13562708/numpy-import-fails-when-embedding-python-in-c