Initialize a sub-module within a package with SWIG and Python 3

匆匆过客 提交于 2020-02-05 07:03:26

问题


I have a C++ application that I swigged to Python 2.7. I'm currently trying to port my code from Python 2.7 to Python 3.4 using the Python/C API and SWIG.

I have a package containing multiple modules. The problem is I cannot find a way to initialize my module ModuleABC as a sub-module of package PackageXYZ. It works well with Python 2.7 but not with Python 3.4 (and I suppose it wouldn't work either with any Python 3.x version).

Here is my code.

ModuleABC.h

extern "C"
{
#if PY_MAJOR_VERSION >= 3
    PyObject* PyInit__ModuleABC(void);
#else
    void init_ModuleABC(void);
#endif
}

void InitModule()
{
 // Defined in the SWIG generated cpp file

#if PY_MAJOR_VERSION >= 3
    PyImport_AppendInittab("PackageXYZ.ModuleABC", PyInit__ModuleABC);
#else
    init_ModuleABC();
#endif
}

PythonManager.cpp

void initPythonInterpreter()
{
    Py_SetPythonHome("C:\Python34");

    Py_SetProgramName("MyApp.exe");

    #if PY_MAJOR_VERSION < 3
       // For Python 2.7 
       Py_Initialize();
    #endif

    // Init module
    ModuleABC.InitModule();

    #if PY_MAJOR_VERSION >= 3
        // For Python 3.4
        Py_Initialize();
    #endif

    int nResult = 0;

    // Import package
    nResult += PyRun_SimpleString("import PackageXYZ");

    // Import module
    // ERROR: Works with Python 2.7, but not with Python 3.4
    nResult += PyRun_SimpleString("import PackageXYZ.ModuleABC");
}

If I change the line:

PyRun_SimpleString("import PackageXYZ.ModuleABC");

to:

PyRun_SimpleString("import ModuleABC");

then it runs with no error, but my module is not imported within the package.

Any ideas?


回答1:


I've finally found the problem. When using PyImport_AppendInittab with SWIG and Python 3 in embedded mode, you need to put the "underscore" before the name of the module, without the package name.

PyImport_AppendInittab("_myModule", PyInit__myModule);

Just make sure your files structure is of the form:

myPackage\
   __init__.py
   myModule.py

Then everything works as expected.



来源:https://stackoverflow.com/questions/24920357/initialize-a-sub-module-within-a-package-with-swig-and-python-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!