其他用户也问过类似的问题,但没有一个答案对我有用。这是我的代码,它的灵感来自 https://ubuntuforums.org/showthread.php?t=1266059
#include <stdio.h>
#include <Python.h>
#include "numpy/arrayobject.h"
int main() {
printf("Embedding Pythonn");
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue, *vec;
const char* script = "TestScript";
const char* function = "Test";
Py_Initialize();
pName = PyUnicode_FromString(script);
pModule = PyImport_Import(pName);
if (pModule != NULL) {
printf("Step-1n");
pFunc = PyObject_GetAttrString(pModule, function);
fflush( stdout );
printf("Step-2n");
if (pFunc && PyCallable_Check(pFunc)) {
// define a vector
double* v = new double[3];
v[0] = 1.0;
v[1] = 2.0;
v[2] = 3.0;
fflush( stdout );
printf("Step-3n");
npy_intp vdim[] = { 3 };
fflush( stdout );
printf("Step-4n");
vec = PyArray_SimpleNewFromData(1, vdim, PyArray_DOUBLE, (void*)v);
fflush( stdout );
printf("Step-5");
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, vec);
PyTuple_SetItem(pArgs, 1, vec);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
Py_DECREF(pName);
if (pValue != NULL) {
printf("Result of call: %fn", PyFloat_AsDouble(pValue));
Py_DECREF(pValue);
}
delete [] v;
} else {
if (PyErr_Occurred()) {
PyErr_Print();
fprintf(stderr, "Cannot find function "%s"n", function);
}
}
} else {
PyErr_Print();
//fprintf(stderr, "Failed to load "%s"n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}
我在 Ubuntu 16.04 上使用 Python3.5 编译此代码。这是编译代码的命令
g++ main.cc -I/usr/include/python3.5m -I/usr/include/python3.5m -Wno-unused-result -Wsign-compare -g -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O3 -Wall -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -L/usr/lib -lpython3.5m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -wl,-O1 -wl,-Bsymbolic-functions -wunused-function
In file included from /usr/include/python3.5m/numpy/ndarraytypes.h:1777:0,
from /usr/include/python3.5m/numpy/ndarrayobject.h:18,
from /usr/include/python3.5m/numpy/arrayobject.h:4,
from main.cc:3: /usr/include/python3.5m/numpy/npy_1_7_deprecated_api.h:15:2: warning:
#warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " ^ In file included from /usr/include/python3.5m/numpy/ndarrayobject.h:27:0,
from /usr/include/python3.5m/numpy/arrayobject.h:4,
from main.cc:3: /usr/include/python3.5m/numpy/__multiarray_api.h:1448:1: warning: ‘int
_import_array()’ defined but not used [-Wunused-function] _import_array(void)
执行时我得到以下输出
Embedding Python
Step-1
Step-2
Step-3
Step-4
Segmentation fault(core dumped)
您需要调用import_array()
函数才能使用 numpy 的 C-API,否则您将看到此类错误。
请参阅 https://docs.scipy.org/doc/numpy/reference/c-api.array.html?highlight=import_array#importing-the-api