首页 > 解决方案 > 不能在 C Python 扩展中使用定义的类型

问题描述

我正在按照C Python 扩展教程创建新类型。我创建了文件custom.csetup.py并将以下行添加到我的CMakeLists.txt

execute_process(WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} COMMAND ${PYTHON_BIN} setup.py build)

但是当我跑步时

Py_Initialize();
PyImport_AddModule("custom"));
PyRun_SimpleString("import custom\nmycustom = custom.Custom()");
PyErr_Print();

Attribute error: module 'custom' has no attribute 'Custom'即使我将生成的 .pyd 的路径添加到sys.path

模块上的 Python 帮助是

Help on module custom:

NAME
    custom

FILE
    (built-in)

我正在使用 Python 3.8 在 Windows 10 上运行

但我可以直接从 Python 终端导入和使用模块

标签: pythonc++python-c-api

解决方案


PyImport_AddModule("custom"));

https://docs.python.org/3/c-api/import.html#c.PyImport_AddModuleObject;这寻找sys.modules“自定义”。如果找不到它,它会创建一个名为“custom”的新空模块。它不搜索文件的路径。

import custom

这寻找sys.modules“自定义”。如果它在那里找到一个模块,那么它会返回它。如果它没有找到一个模块,那么它会在 Python 路径中搜索一个合适的模块。

您正在以编程方式创建一个空白模块,并且正在使用它而不是 Python 路径上的模块。


推荐阅读