编写扩展时,如何在Python和C之间传递空指针? [英] How do you pass around a void pointer between Python and C when writing an extension?
问题描述
今天我开始了我的第一个Python扩展,只是作为练习在C库周围创建了一个很小的包装器.与C库一样,您通常从初始化函数开始,该函数产生一个处理程序.您可以将该处理程序传递给函数,然后再将其传递给清除函数以释放内存.
I started on my first Python extension today and was only creating a very small wrapper around a C library as an exercise. As is typical with C libraries, you start of with an initialization function that yields a handler. You can pass that handler to functions and later you pass it to the cleanup function that frees memory.
当我开始编写包装器时,我基本上希望有一种方法可以从python调用每个本机C函数.很快,我遇到了一个问题,我需要将任意指针从C返回到Python,而仅在另一个函数中将其从该指针再次返回给C.我没关系,因为我没有在Python中使用它,我只是存储它并传递它.
When I started writing the wrapper I basically wanted to have a way to call each native C function from python. Quickly I hit the problem that I need to return an arbitrary pointer from C to Python only to give it from there to C again in another function. I doesn't matter how it looks as I don't use it in Python, I just store it and pass it around.
那么如何在Python和C之间传递空指针?
So how do you pass around a void pointer between Python and C?
请注意:我知道不建议您使用扩展系统编写此类小型包装,而建议使用ctypes和朋友.这只是现在的练习.
Please note: I know it is not recommended to write such small wrappers using the extension system but rather ctypes and friends. This is just for practice right now.
推荐答案
PyLong_FromVoidPtr()和PyLong_AsVoidPtr()可能会被滥用以将恶意数据注入您的程序.我建议反对他们.
PyLong_FromVoidPtr() and PyLong_AsVoidPtr() can be abused to inject malicious data into your program. I recommend against them.
Python具有PyCapsule来完成该工作.胶囊提供了一种在模块或Python空间与C空间之间交换void ptr的安全方法.胶囊也是类型安全的.如果需要一些示例,socket/ssl模块和pyexpat/_elementtree模块使用胶囊交换CAPI结构.
Python has PyCapsule for exactly that job. Capsules provide a safe way to exchange void ptr between modules or Python space and C space. The capsules are type-safe, too. If you need some example, the socket / ssl modules and pyexpat / _elementtree modules use capsules to exchange CAPI structs.
http://docs.python.org/3/c-api/capsule.html
这篇关于编写扩展时,如何在Python和C之间传递空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!