英文:
Access application data when extending embedded Python
问题
我正在编写一个嵌入Python解释器的应用程序。该应用程序还通过自定义模块扩展了Python。这是根据Python文档中的“扩展和嵌入Python解释器”部分完成的。在“扩展嵌入式Python”部分,他们描述了如何“访问应用程序的功能”,以及示例模块emb
如何通过使用静态变量numargs
来访问应用程序的main
函数的argv
。
现在,我的问题是,我是否可以以比使用全局状态更封装的方式将数据(如argv
)传递给我的模块?
与emb
示例不同,我使用了多阶段初始化,并通过PyModuleDef
实例中的m_size
引入了模块状态的结构。因此,我希望以某种方式将数据传递给我的Py_mod_exec
插槽函数,以在我的模块状态中设置它,但由于使用原始的C函数指针进行设置,我无法看到以这种方式传递数据的方法。另外,我考虑在Py_Initialize
调用后查找模块,然后通过PyModule_GetState
传递数据,但我不知道如何查找我的多阶段初始化的模块。因此,我现在的想法是在解释器的某个地方设置一些全局状态,并通过这种方式传递数据。但我还没有深入研究这个问题,因为我希望有一个更好的解决方案。
英文:
I am writing an application that embeds a Python interpreter. The application also extends Python with a custom module. This is done along the lines of the "Extending and Embedding the Python Interpreter" part of the Python documentation. In the section "Extending Embedded Python" they describe how to "access to functionality from the application" and the example module emb
get access to argv
of the application's main
function by using a static variable numargs
.
Now, my question is, can I somehow pass data (like argv
) to my module in a more encapsulated way than using global state?
In contrast to the emb
example, I use multi-phase initialization and introduce module state in a struct via m_size
in my PyModuleDef
instance.
So I would have liked to somehow pass data to my Py_mod_exec
slot function to set it in my module state, but as the setup is made with raw C function pointers, I cannot see a way to pass data that way.
Alternatively, I've thought looking up the module after my Py_Initialize
call and pass the data via PyModule_GetState
, but I don't see how I can lookup my multi-phase initialized module.
So my idea now is to set some global state somewhere on the interpreter and pass the data that way. But I have not looked much into that yet, as I was hoping for a better solution.
答案1
得分: 0
Alternatively, I've thought looking up the module after my Py_Initialize
call and pass the data via PyModule_GetState
, but I don't see how I can lookup my multi-phase initialized module.
I ended up with that solution and used PyImport_ImportModule
to get a reference to the module.
See discussion on https://discuss.python.org/t/access-application-data-when-extending-embedded-python.
英文:
> Alternatively, I've thought looking up the module after my
> Py_Initialize
call and pass the data via PyModule_GetState
, but I
> don't see how I can lookup my multi-phase initialized module
I ended up with that solution and used PyImport_ImportModule
to get a reference to the module.
See discussion on https://discuss.python.org/t/access-application-data-when-extending-embedded-python.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论