在C中嵌入python时,numpy导入失败 [英] Numpy import fails when embedding python in c
问题描述
我正在尝试将python程序嵌入到c ++代码中.我的问题是使用包含numpy导入的python脚本. 例如,如果我使用以下c ++代码
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;
}
具有以下包含函数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
,则它将失败
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)
推荐答案
我认为您是静态链接,但未保留所有符号,而这些符号是加载动态扩展模块(即-Xlinker -export-dynamic
)所必需的.请参见链接要求,该指南建议您从以下位置查询正确的选项: distutils.sysconfig.get_config_var('LINKFORSHARED')
.
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')
.
顺便说一句,可变参数函数 Py_BuildValue
是一个创建args
的更方便的方法.
BTW, the variadic function Py_BuildValue
is a more convenient way to create args
.
这篇关于在C中嵌入python时,numpy导入失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!