我正在开始用 C 编写 Python 3 模块的过程。我编写的 C 已经编译得很好(我在帖子底部编译的代码)。我编译:
python3 setup.py build_ext --inplace
构建好的.so文件放在当前目录下。启动 python3 后,当我导入模块时,出现此错误(三个点用于截断路径):
>>> import helloWorld
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(..., 2): Symbol not found: _Py_InitModule4_64
Referenced from: .../helloWorld.cpython-36m-darwin.so
Expected in: flat namespace
in .../helloWorld.cpython-36m-darwin.so
如何实现符号_Py_InitModule4_64?
如果这意味着什么,我正在运行 macOS High Sierra
<小时/>对helloWorld.cpython-36m-darwin.so运行nm显示_Py_InitModule4_64未定义,那么这是否证明编译过程中存在问题?
nm helloWorld.cpython-36m-darwin.so
U _Py_BuildValue
U _Py_InitModule4_64
0000000000000eb0 t _helloWorld
0000000000001060 d _helloWorld_docs
0000000000001020 d _helloworld_funcs
0000000000000e80 T _inithelloWorld
U dyld_stub_binder
代码
测试.c:
#include <Python/Python.h>
static PyObject* helloWorld(PyObject* self) {
return Py_BuildValue("s", "Hello, Python extensions!!");
}
static char helloWorld_docs[] =
"helloWorld( ): Any message you want to put here!!\n";
static PyMethodDef helloworld_funcs[] = {
{"helloWorld", (PyCFunction)helloWorld,
METH_NOARGS, helloWorld_docs},
{NULL}
};
void inithelloWorld(void) {
Py_InitModule3("helloworld", helloworld_funcs, "Extension module example!");
}
设置.py:
from distutils.core import setup, Extension
setup(name = 'helloWorld', version = '1.0', \
ext_modules = [Extension('helloWorld', ['test.c'])])
最佳答案
您针对 Python 2 C API 编写了模块(the various Py_InitModule
functions 纯粹用于 Python 2),但您尝试使用 Python 3 编译并运行它。CPython 的 C 层发生了很多变化 在 Python 2 和 3 之间,据我所知,没有用于 C 代码的 2to3
工具。
您需要编写 Python 3 API 兼容代码才能在 Python 3 上工作;最简单的(也是 3.0-3.4 上支持的唯一方法)翻译是 single-phase initialization (使用PyModule_Create
),但是 multi-phase initialization获得的行为更像Python中定义的模块(例如,可以以单相模块不可能的方式完全卸载它们)。入口点名称的结构也发生了变化,从 initMODULENAME
更改为 PyInit_MODULENAME
,因此您也需要更新它。
关于python - C Python 模块——导入错误 : Symbol not found: _Py_InitModule4_64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960112/