使用 SWIG 和 Python 3 初始化包中的子模块 [英] Initialize a sub-module within a package with SWIG and Python 3

查看:25
本文介绍了使用 SWIG 和 Python 3 初始化包中的子模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Python 2.7 的 C++ 应用程序.我目前正在尝试使用 Python/C API 和 SWIG 将我的代码从 Python 2.7 移植到 Python 3.4.

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.

我有一个包含多个模块的包.问题是我找不到将我的模块 ModuleABC 初始化为包 PackageXYZ 的子模块的方法.它适用于 Python 2.7,但不适用于 Python 3.4(我想它也不适用于任何 Python 3.x 版本).

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).

这是我的代码.

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");
}

如果我换行:

PyRun_SimpleString("import PackageXYZ.ModuleABC");

到:

PyRun_SimpleString("import ModuleABC");

然后它运行没有错误,但我的模块没有导入包中.

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

有什么想法吗?

推荐答案

我终于找到了问题所在.在嵌入模式下将 PyImport_AppendInittab 与 SWIG 和 Python 3 一起使用时,您需要将下划线"放在模块名称之前,没有包名称.

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.

这篇关于使用 SWIG 和 Python 3 初始化包中的子模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆