C Python 模块 — 导入错误:找不到符号:_Py_InitModule4_64

我正在开始用 C 编写 Python 3 模块的过程。 CI 编写的已经编译良好(我在帖子底部编译的代码)。我编译:


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'])])


qq_花开花谢_0
浏览 771回答 1
1回答

慕婉清6462132

您针对 Python 2 C API 编写了您的模块(各种Py_InitModule函数纯粹用于 Python 2),但是您正在尝试编译它并使用 Python 3 运行它。CPython 的 C 层在 Python 2 和 3 之间发生了很大变化,据2to3我所知,没有用于 C 代码的工具。您需要编写与 Python 3 API 兼容的代码才能在 Python 3 上工作;最简单的(也是 3.0-3.4 支持的唯一方法)转换是单阶段初始化(使用PyModule_Create),但多阶段初始化的行为更像是 Python 中定义的模块(例如,可以以某种方式完全卸载它们)单相模块可能)。入口点名称的结构也发生了变化,从initMODULENAME到PyInit_MODULENAME,因此您也需要对其进行更新。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python