Устранено это по-другому: Проблема в том, что атрибут модуля __dict__
доступен только для чтения.
Я использую python/c api для 2.7.5. После использования PyModule_New
не было обеспечения для выполнения какого-либо кода в __dict__
для импорта в api. Поэтому я использовал другой подход.
Я создал модуль, использующий код python, а не python/c api. У которого есть возможность выполнить некоторый код в словаре модулей exec 'import sys' in mymod.__dict__
.
Импорт sys
предоставляет вновь созданному модулю доступ к sys.modules
, который имеет все доступные модули. Поэтому, когда я делаю другой импорт, программа знает, где искать путь для импорта. Вот код.
PyRun_SimpleString("import types,sys");
//create the new module in python
PyRun_SimpleString("mymod = types.ModuleType(\"mymod\")");
//add it to the sys modules so that it can be imported by other modules
PyRun_SimpleString("sys.modules[\"mymod\"] = mymod");
//import sys so that path will be available in mymod so that other/newly created modules can be imported
PyRun_SimpleString("exec 'import sys' in mymod.__dict__");
//import it to the current python interpreter
pNewMod=PyImport_Import(PyString_FromString("mymod"));
//get the dict of the new module
pLocal = PyModule_GetDict(pNewMod);
//run the code that you want to be available in the newly created module.
//python_script has the code that must be injected into the new module.
//all your imports will work fine from now on.
//Provided that you have created them before importing sys in to the new module
PyRun_String(python_script, Py_file_input, pGlobal, pLocal);