在 Python 中访问空指针(使用 SWIG 或其他东西) [英] Accessing void pointers in Python (using SWIG or something else)
问题描述
我一直在尝试使用 SWIG 来包装一个简单的库,该库使用 ioctl() 来填充如下所示的结构:
I've been trying to use SWIG to wrap around a simple library that uses ioctl() to populate a structure like the following:
struct data
{
header* hdr;
void* data;
size_t len;
};
data 是指向缓冲区的指针,len 是该缓冲区的长度.
data is a pointer to a buffer, len is the length of that buffer.
我不知道如何将数据转换为 Python 字符串(或数组).此外,我需要一种方法来释放析构函数中的缓冲区.任何建议表示赞赏.
I'm unable to figure out how to convert data to a Python string (or array). Furthermore, I need a way to free that buffer in the destructor. Any suggestions are appreciated.
推荐答案
既然你在 Q 的标题中说了或者别的什么"——如果你选择使用 ctypes,你可以用 c_void_p
表示一个 void*
(ctypes 的一种 基本数据类型, 并从 C 运行时库中访问诸如 free
和 memcpy
之类的函数(只要后者可用作 DLL/.so 动态库,但这种情况非常广泛)天).要获得一个可变字符缓冲区,您可以在其中 memcpy
数据,请使用 create_string_buffer.
Since you say "or something else" in the Q's title -- if you choose to use ctypes, you can represent a void*
with c_void_p
(one of ctypes' fundamental data types, and access functions such as free
and memcpy
from the C runtime library (as long as the latter's available as a DLL / .so dynamic library, but that's true pretty widely these days). To get a mutable character buffer into which you can memcpy
the data, use create_string_buffer.
当然,您也可以使用 Python C API -- PyByteArray_FromStringAndSize 是你在这种情况下用来从你的 void*
和长度制作一个字节数组副本(当然你会在适当的时候直接调用 free
,因为它只是 C 代码).
Of course you could alternatively use the Python C API -- PyByteArray_FromStringAndSize is what you'd use in this case to make a byte array copy from your void*
and length (and of course you'd call free
directly, when appropriate, since it's just C code anyway).
另一种可以考虑的可能性是 Cython,一种类似 Python 的语言,旨在编写 Python 扩展,并且Cython 编译器可以从 Cython 源代码生成可编译的 C 代码 - 在 Cython 中,您的 struct
将是:
Another possibility to consider is Cython, a Python-like language designed to write Python extensions and such that the Cython compiler can generate compilable C code from Cython sources - in Cython, your struct
would be:
cdef struct data:
void* hdr
void* data
unsigned int* len
假设您不想麻烦地声明 header
(即,这里只有 data
和 len
对您很重要) -- size_t
,我相信,现在不是 Cython 的一部分(我可能是错的,他们确实不断添加东西;-),但是 unsigned int
可能可以做.
assuming you don't want to go to the trouble of declaring header
(i.e., that only data
and len
matter to you here) -- size_t
, I believe, is not part of Cython at this time (I could be wrong, they do keep adding stuff;-), but unsigned int
can probably do.
抱歉,自从我认真使用 SWIG 已经太久了(所有这些优秀的替代品是什么)——如果不是标题中那个诱人的或其他"条款,我会跳过 Q;-).
Sorry, it's been too long since I used SWIG in earnest (what with all these excellent alternatives) -- I'd have skipped the Q were it not for that tempting "or something else" clause in the title;-).
这篇关于在 Python 中访问空指针(使用 SWIG 或其他东西)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!