【问题标题】:Can't use defined type in C Python extension不能在 C Python 扩展中使用定义的类型
【发布时间】:2021-11-22 02:28:54
【问题描述】:

我正在关注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();

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

模块的 Python 帮助是

Help on module custom:

NAME
    custom

FILE
    (built-in)

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

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

【问题讨论】:

  • 或许this可以帮到你
  • 不,它没有:/ 仍然出现属性错误
  • 这不是很完整...(请参阅minimal reproducible example)您必须按照该外部链接中的说明重新创建错误。
  • 也许检查你构建程序的“当前文件夹”是否恰好有一个名为custom.py的文件,或者你没有一个名为custom的包?跨度>

标签: python c++ python-c-api


【解决方案1】:
PyImport_AddModule("custom"));

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

import custom

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2023-03-27
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多