我试图从JNI库调用python。这可以按预期工作,并感谢互联网上的所有信息。
当我尝试“将numpy导入为np”时,我的问题就出现了。当我在任何python脚本中包含它时,下面代码中的PyImport_Import(pName)返回null。如果没有检查null,程序(预期)会发出分段违规。
我使用的是Java 7(openjdk-amd64),Ubuntu 13.04,gcc 4.7.3
下面的代码是python解释器初始化和调用的片段。它被编译成Java加载的共享对象。如果普通程序中包含相同的代码,则python脚本将按预期运行。
我的猜测是numpy无法加载通过java和共享JNI库运行时所需的库。但是经过48小时的工作,我对于我需要说些什么才能让它发挥作用一无所知。
int call_python(char *module, char *function, PyObject *list)
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
Py_Initialize();
printf("Initialized\n");
pName = PyString_FromString(module);
printf("pName created from: '%s'\n", module);
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyRun_SimpleString("sys.path.append(\"/home/jonathan/swigtests/j2p\")");
PyRun_SimpleString("print \"Interpreter Running\"");
pModule = PyImport_Import(pName);
if (pModule == (PyObject *)NULL)
{
printf("Unable to load '%s'\n", module);
return 0;
}
printf("Checking pmodule...%x\n", (int)pModule);
if (!PyModule_Check(pModule))
printf("pModule is not a module!\n");
else
printf("pModule is a module!\n");
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, function);
PyObject *arglist = Py_BuildValue("(i)", 1);
PyDict_SetItemString(pDict, "field", list);
if (PyCallable_Check(pFunc))
{
printf("Calling Python\n");
//if (PyObject_CallFunction(pFunc, "i", 2) == NULL)
if (PyObject_CallObject(pFunc, arglist) == NULL)
printf("CallFunction failed\n");
else
printf("CallFunction succeeded\n");
}
else
{
printf("Not callable\n");
PyErr_Print();
}
printf("Python done\n");
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
return 0;
}
更新。我在printf之后添加了PyErr_Print(“无法加载”)...这会产生有用的回溯打印输出:
Traceback (most recent call last):
File "./py_function.py", line 3, in <module>
import numpy as np
File "/usr/lib/python2.7/dist-packages/numpy/__init__.py", line 137, in <module>
import add_newdocs
File "/usr/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "/usr/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 4, in <module>
from type_check import *
File "/usr/lib/python2.7/dist-packages/numpy/lib/type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "/usr/lib/python2.7/dist-packages/numpy/core/__init__.py", line 5, in <module>
import multiarray
ImportError: /usr/lib/python2.7/dist-packages/numpy/core/multiarray.so: undefined symbol: PyExc_SystemError
这开始看起来像使用DateTime报告的另一个问题:
https://mail.python.org/pipermail//capi-sig/2013-August/000600.html
与此问题完全相同:
How to allow 3rd-party libraries to be imported by scripts called in embedded Python interpreter?