1

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?

2
  • Why are you using PyRun_SimpleString instead of PyImport_ImportModule? Commented Jul 23, 2014 at 20:37
  • Just because I was doing some tests. Both commands give same results. Commented Jul 23, 2014 at 20:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.