我正在C函数中调用python代码,它工作正常。但是,我想从python调用C函数(有效地重用所有C代码),但是从C导入python模块时,我得到了一个段。错误
(从代码中删除了所有错误检查,以使其变得更简单)
#include "Python.h"
int runpython() {
Py_Initialize();
PyObject* pFunc;
PyObject *pArgs;
PyObject *pValue;
PyObject* pName = PyString_FromString("python_module");
PyObject* pModule = PyImport_Import(pName);
Py_DECREF(pModule);
pFunc = PyObject_GetAttrString(pModule, "pcall");
pArgs = PyTuple_New(1);
pValue = PyInt_FromLong(42);
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
Py_DECREF(pValue);
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
int main() {
return runpython();
}
def pcall(value):
print "Value: " + str(value)
from ctypes import *
cdll.LoadLibrary("libMyPython.so")
libc = CDLL("libMyPython.so")
libc.runpython()
export PYTHONPATH=$PYTHONPATH:$PWD
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD
echo "Running C main"
gcc main.c -o main -I/usr/include/python2.7 -lpython2.7 -g
./main
echo "Running Python main"
gcc -shared -fPIC main.c -o libMyPython.so -I/usr/include/python2.7 -lpython2.7 -g
python python_main.py
示例输出为:
### Running C main
Value: 42
### Running Python main
Segmentation fault (core dumped)
在gdb中运行会产生堆栈:
Program received signal SIGSEGV, Segmentation fault.
0x00005555556318d9 in PyImport_Import ()
(gdb) bt
#0 0x00005555556318d9 in PyImport_Import ()
#1 0x00007ffff5e07883 in runpython () at c_main.c:9
#2 0x00007ffff600edae in ffi_call_unix64 () from /usr/lib/x86_64-linux-gnu/libffi.so.6
#3 0x00007ffff600e71f in ffi_call () from /usr/lib/x86_64-linux-gnu/libffi.so.6
#4 0x00007ffff6221e56 in _ctypes_callproc ()
from /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
#5 0x00007ffff6221505 in ?? () from /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
#6 0x000055555564f420 in PyEval_EvalFrameEx ()
#7 0x0000555555647d0a in PyEval_EvalCodeEx ()
#8 0x0000555555647629 in PyEval_EvalCode ()
#9 0x000055555567861f in ?? ()
#10 0x0000555555673322 in PyRun_FileExFlags ()
#11 0x000055555567267d in PyRun_SimpleFileExFlags ()
#12 0x00005555556211ab in Py_Main ()
#13 0x00007ffff7a05b97 in __libc_start_main (main=0x555555620b10 <main>, argc=2,
argv=0x7fffffffde58, init=<optimised out>, fini=<optimised out>, rtld_fini=<optimised out>,
stack_end=0x7fffffffde48) at ../csu/libc-start.c:310
#14 0x0000555555620a2a in _start ()
我尝试使用PyImport_ImportModule
或PyRun_SimpleString("import python_module")
来达到相同的效果...有什么想法吗?
我正在使用python2.7在ubuntu机器上运行它。