Import fuzzy copies when embedding python in c

I am trying to embed a python program in C ++ code. the problem is using a python script that contains numpy imports. 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 that contain the derive function

 def derive(x,xp,dt,y,yp,dz): return log(abs(x - xp)/dt),exp((y-yp)/dz) 

it works correctly, but if log.py contains 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) 
+6
source share
1 answer

I think you are linking statically, but not retaining all the characters needed to load dynamic extension modules (i.e. -Xlinker -export-dynamic ). See Requirement Binding , which recommends that you request the correct parameters from distutils.sysconfig.get_config_var('LINKFORSHARED') .

By the way, the variational function Py_BuildValue is a more convenient way to create args .

+2
source

All Articles