【问题标题】:translating arrays from c to python ctypes将数组从 c 转换为 python ctypes
【发布时间】:2010-10-13 09:27:22
【问题描述】:

我在 C 上有以下数组,我如何将它们与 structre 中的 ctypes 数据类型进行交互

struct a {

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

我是否应该将固定数组作为数据类型 * 我想要的大小如下所示,如果是,我该怎么做 将此结构称为 fun 的参数,从该结构中获取实例

class a(structure) :

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

【问题讨论】:

    标签: python ctypes


    【解决方案1】:

    你在正确的轨道上。您可能只是缺少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
    

    【讨论】:

      【解决方案2】:

      这应该可行:

      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
      

      【讨论】:

        猜你喜欢
        • 2011-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-20
        • 2018-12-24
        • 1970-01-01
        相关资源
        最近更新 更多