【问题标题】:Create a Python3 module at runtime while initialize an embedded Python在初始化嵌入式 Python 时在运行时创建 Python3 模块
【发布时间】:2013-08-07 15:43:25
【问题描述】:

我们有一个实现自定义编程语言的 DLL。我想要做的是添加对 python 语言的支持,为“API 函数”保持相同的代码。

我已经成功地在这个 DLL 中嵌入了 python,现在我正在解决这个问题,将所有旧函数公开为一个 python 模块。

现在这个 DLL 没有将 API 函数公开为接口函数,而是安装(作为函数指针)到语言引擎。这样就不可能创建一个新的 python 模块(一个新的 DLL)。但是我需要保持与旧方法的兼容性...

是否可以在运行时创建(并安装)在 Python 所在的同一个 DLL 中定义的模块?

我想像在 PyInitialize(); 之后调用 PyInit_xxxx 方法;

【问题讨论】:

    标签: c++ python embedding extending


    【解决方案1】:

    这在 Python 3 中变得更加复杂(与在 Python 2 中的情况相比),但我已经让它适用于我的代码,所以我希望这也适用于你。

    // Python 3's init function must return the module's PyObject* made 
    // with PyModule_Create()
    PyObject* initspam(); 
    const char* spam_module_name;
    
    int main(int argc, char **argv)
    {
        Py_Initialize();
    
        PyImport_AddModule(spam_module_name);
        PyObject* module = initspam();
    
        PyObject* sys_modules = PyImport_GetModuleDict();
        PyDict_SetItemString(sys_modules, spam_module_name, module);
        Py_DECREF(module)
    
        ...
    }
    

    我在python 3源代码中找到了一个这样的例子:

    Python-3.4.2\Python\pythonrun.c : import_init()

    这比我上面的例子有更好的错误检查。

    【讨论】:

      【解决方案2】:

      我已经用这样的代码解决了之前 Py_Initialize();

      /* Add a built-in module, before Py_Initialize */
      PyImport_AppendInittab("xxx", PyInit_xxx);
      

      【讨论】:

        【解决方案3】:

        处理此问题的最简单方法是在调用 Py_Initialize() 或 PyMac_Initialize() 之后直接调用 initspam() 来静态初始化静态链接模块:

        int main(int argc, char **argv)
        {
            /* Pass argv[0] to the Python interpreter */
            Py_SetProgramName(argv[0]);
        
            /* Initialize the Python interpreter.  Required. */
            Py_Initialize();
        
            /* Add a static module */
            initspam();
        

        可以在 Python 源代码分发的 Demo/embed/demo.c 文件中找到一个示例。

        【讨论】:

        • 欢迎来到 Stack Overflow!很高兴看到第一篇文章是一个答案,继续努力:)
        • 那个演示是针对 Python 2...Python 3 更复杂。
        猜你喜欢
        • 1970-01-01
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-27
        相关资源
        最近更新 更多