简体   繁体   English

Python / C-Api:将类添加到模块

[英]Python / C-Api: Add class to module

Im currently trying to embed the python interpreter into my application. 我目前正在尝试将python解释器嵌入到我的应用程序中。 Because my application uses the Poco API for logging, I want to make it accessable through the logging module in python too. 因为我的应用程序使用Poco API进行日志记录,所以我也想通过python中的日志记录模块对其进行访问。 The most easiest way for me to do this, is to provide a static set of function as an extension module to log a message and then to write a Handler subclass calling these functions. 对于我而言,最简单的方法是提供一组静态函数作为扩展模块,以记录消息,然后编写调用这些函数的Handler子类。

Since I dont want the user to install any additional python modules and since I dont have the requirement to reuse my code outside of my embedded python interpreter, it would be great if one could just provide the static functions through Py_InitModule() and then to add a hardcoded Handler subclass to the created module (hardcoded means: added at runtime but actually a const string which gets always interpreted at initialization). 由于我不希望用户安装任何其他的python模块,并且由于我不需要在嵌入式python解释器之外重用我的代码,因此如果人们可以只通过Py_InitModule()提供静态函数然后添加创建模块的硬编码处理程序子类(硬编码意味着:在运行时添加,但实际上是一个常量字符串,始终在初始化时进行解释)。

My problem is that I dont know how to interpret a normal python class definition, eg: 我的问题是我不知道如何解释普通的python类定义,例如:

class Test:
    someVar=1

so that it is added to a given module and then accesable as, eg mymodule.Test 以便将其添加到给定的模块中,然后以例如mymodule.Test身份访问

A solution can either be pure python based or work with the python c-api. 解决方案可以是基于纯python的,也可以与python c-api一起使用。

I finally found the answere myself: There are actually 2 methods to execute code in the context of a module 我终于找到了自己的答案:实际上,有两种方法可以在模块的上下文中执行代码

Way 1 方式1

PyObject* module = Py_InitModule("poco",LoggingPocoMethods);
PyObject* code = Py_CompileString("class Test:\n\tdef __repr__(self):\n\t\treturn 'Hello world'","",Py_file_input);
PyImport_ExecCodeModule("poco",code);

This method has the drawback that the module will be reloaded which is not required at this stage. 这种方法的缺点是模块将被重新加载,这在现阶段是不需要的。

Way 2 方式二

PyObject* module = Py_InitModule("poco",LoggingPocoMethods);
PyObject* mainModule = PyImport_AddModule("__main__");

PyObject* dict = PyModule_GetDict(module);
PyObject* mainDict = PyModule_GetDict(mainModule);

PyRun_String("def test():\n\tprint 'test'\n",Py_file_input,mainDict,dict);

To put something into a module, just assign it. 要将某些内容放入模块中,只需对其进行分配即可。 Assuming class Test is defined as above, to attach it to module mymodule under that name, just write 假设类Test的定义如上所述,要将其以该名称附加到模块mymodule,只需编写

mymodule.Test = Test

That's it. 而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM