adub
adub

Reputation: 63

Can't use defined type in C Python extension

I'm following the C Python extension tutorial to create new type. I created the file custom.c, setup.py and added the following line to my CMakeLists.txt:

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

But when I run

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

I got Attribute error: module 'custom' has no attribute 'Custom' even if I add the path to generated .pyd to sys.path

Python help on module is

Help on module custom:

NAME
    custom

FILE
    (built-in)

I am running on Windows 10 with Python 3.8

But I can import and use the module directly from a Python terminal

Upvotes: 2

Views: 144

Answers (1)

DavidW
DavidW

Reputation: 30935

PyImport_AddModule("custom"));

See https://docs.python.org/3/c-api/import.html#c.PyImport_AddModuleObject; this looks in sys.modules for "custom". If it can't find it then it creates a new empty module named "custom". It does not search the path for files.

import custom

This looks in sys.modules for "custom". If it finds a module there then it returns it. If it doesn't find a module then it searches the Python path for a suitable module.

You're programmatically creating a blank module, and that is getting used instead of the module on the Python path.

Upvotes: 1

Related Questions