不能在 C Python 扩展中使用定义的类型

Can't use defined type in C Python extension

我正在按照 C Python extension tutorial 创建新类型。 我创建了文件 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)

我 运行宁 Windows 10 Python 3.8

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

PyImport_AddModule("custom"));

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

import custom

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

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