python - 不能在 C Python 扩展中使用定义的类型
问题描述
我正在按照C Python 扩展教程创建新类型。我创建了文件custom.c
,setup.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 终端导入和使用模块
解决方案
PyImport_AddModule("custom"));
见https://docs.python.org/3/c-api/import.html#c.PyImport_AddModuleObject;这寻找sys.modules
“自定义”。如果找不到它,它会创建一个名为“custom”的新空模块。它不搜索文件的路径。
import custom
这寻找sys.modules
“自定义”。如果它在那里找到一个模块,那么它会返回它。如果它没有找到一个模块,那么它会在 Python 路径中搜索一个合适的模块。
您正在以编程方式创建一个空白模块,并且正在使用它而不是 Python 路径上的模块。
推荐阅读
- python - 全局变量不会从各种不同的文件中改变
- css - 添加 data-live-search="true" 时 html 选择选项样式错误
- android - Android 不同的屏幕尺寸
- angularjs - 使用角度错误
- python-3.x - Python pathlib - 这是以独立于平台的方式加入路径的正确方法吗?
- object - git 如何解析树对象的内容?
- python-3.x - Azure 服务总线 - 获取待处理和正在处理的消息的计数
- android - 在firebase db中成功认证后没有获得facebook的电子邮件ID
- angular - 带有 Tailwind CSS、PostCSS、SCSS 和 MiniCssExtractPlugin 的 Angular 9 无法编译
- python - 如何使用 pandas.read_excel 重命名索引列