将数组从C转换为Python ctypes

2 投票
2 回答
2106 浏览
提问于 2025-04-16 05:25

我在C语言中有下面这些数组,我该如何把它们转成ctypes的数据类型,并放进结构体里呢?

struct a {

BYTE    a[30];
CHAR    b[256];
};

我是不是应该把一个固定大小的数组理解为数据类型乘以我想要的大小,就像下面这样?如果是的话,我该如何把这个结构体作为参数传给一个需要这个结构体实例的函数呢?

class a(structure) :

_fields_ = [ ("a",c_bytes*30 ),
                 ("b",c_char*256 ),]

2 个回答

0

这个应该可以正常工作:

from ctypes import Structure, c_bytes, c_char

class A(Structure):
    _fields_ = [("a", c_bytes*30), ("b", c_char*256)]

然后你可以通过点操作符简单地访问结构体中的字段:

>>> my_a = A()
>>> my_a.a[4] = 127
>>> my_a.a[4]
127
>>> my_a.b = "test string"
>>> my_a.b
'test string'
>>> my_a.b[2]
's'

你还可以直接把这个结构体传递给任意的Python函数:

def my_func(a):
    print "a[0] + a[1] = %d" % (a.a[0] + a.a[1], )
    print "Length of b = %d" % len(a.b)

>>> my_a = A()
>>> my_a.a[0:2] = 19, 23
>>> my_a.b = "test"
>>> my_func(my_a)
a[0] + a[1] = 42
Length of b = 4
3

你走在正确的道路上。你可能只是缺少了 byref() 这个函数。假设你想调用的函数叫做 *print_struct*,那么你可以这样做:

from ctypes import *

class MyStruct(Structure):
    _fields_ = [('a',c_byte*30), ('b',c_char*256)]

s = MyStruct() # Allocates a new instance of the structure from Python

s.a[5] = 10 # Use as normal

d = CDLL('yourdll.so')
d.print_struct( byref(s) )  # byref() passes a pointer rather than passing by copy

撰写回答