简体   繁体   English

在两个python模块之间传递C函数指针

[英]Passing C function pointers between two python modules

I'm writing an application working with plugins. 我正在编写一个使用插件的应用程序。 There are two types of plugins: Engine and Model . 有两种类型的插件: EngineModel Engine objects have an update() method that call the Model.velocity() method. Engine对象具有一个update()方法,该方法调用Model.velocity()方法。

For performance reasons these methods are allowed to be written in C. This means that sometimes they will be written in Python and sometimes written in C. 出于性能方面的考虑,这些方法允许用C编写。这意味着它们有时会用Python编写,有时会用C编写。

The problem is that this forces to do an expensive Python function call of Model.velocity() in Engine.update() (and also reacquiring the GIL). 问题在于,这迫使在Model.velocity()中执行Engine.update()的昂贵的Python函数调用(并且还要重新获取GIL)。 I thought about adding something like Model.get_velocity_c_func() to the API, that would allow Model implementations to return a pointer to the C version of their velocity() method if available, making possible for Engine to do a faster C function call. 我曾考虑过向API添加诸如Model.get_velocity_c_func()类的东西,这将允许Model实现返回指向其velocity()方法的C版本的指针velocity()如果有的话),从而使Engine可以更快地进行C函数调用。

What data type should I use to pass the function pointer ? 我应该使用哪种数据类型来传递函数指针? And is this a good design at all, maybe there is an easier way ? 这是一个好的设计,也许有更简单的方法吗?

The CObject (PyCOBject) data type exists for this purpose. 为此存在CObject(PyCOBject)数据类型。 It holds a void*, but you can store any data you wish. 它包含一个void *,但您可以存储所需的任何数据。 You do have to be careful not to pass the wrong CObject to the wrong functions, as some other library's CObjects will look just like your own. 您一定要小心,不要将错误的CObject传递给错误的函数,因为其他一些库的CObject看起来就像您自己的。

If you want more type security, you could easily roll your own PyType for this; 如果您想要更高的类型安全性,则可以为此轻松滚动自己的PyType; all it has to do, after all, is contain a pointer of the right type. 毕竟,它所要做的就是包含正确类型的指针。

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

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