具有函数和python ctypes的结构

时间:2017-06-15 02:46:06

标签: python c ctypes

我有一个c库,我想用python 2.7 ctypes包装。

typedef struct SRSLTE_API{
  void *ptr;
  uint32_t R;
  uint32_t K;
  uint32_t framebits;
  bool tail_biting;
  float gain_quant; 
  int16_t gain_quant_s; 
  int (*decode) (void*, uint8_t*, uint8_t*, uint32_t);
  int (*decode_f) (void*, float*, uint8_t*, uint32_t);
  void (*free) (void*);
  uint8_t *tmp;
  uint8_t *symbols_uc;
}srslte_viterbi_t;

如何在python中创建此结构?这就是我现在所拥有的。

from ctypes import *
class srslte_viterbi_t(Structure):
    _fields_ = [("ptr", c_void_p),
                ("R", c_uint),
                ("K", c_uint),
                ("framebits", c_uint),
                ("tail_biting", c_bool),
                ("gain_quant", c_float),
                ("gain_quant_s", c_short),
                ("decode", POINTER(c_int)),
                ("decode_f", POINTER(c_int)),
                ("free", c_void_p),
                ("tmp", POINTER(c_ubyte)),
                ("symbols_uc", POINTER(c_ubyte))
                ]
viterbi_t = srslte_viterbi_t(None, c_uint(0), c_uint(0), c_uint(0), 
    c_bool(False), c_float(0.0), c_short(0), None, None, None, None, None)

此结构编译但未给出正确的结果。我担心我没有正确分配解码功能?什么是行

int (*decode) (void*, uint8_t*, uint8_t*, uint32_t);

无论如何都在做一个结构?

1 个答案:

答案 0 :(得分:2)

这是结构的正确定义:

from ctypes import *

class srslte_viterbi_t(Structure):
    _fields_ = [
        ('ptr',c_void_p),
        ('R',c_uint32),
        ('K',c_uint32),
        ('framebits',c_uint32),
        ('tail_biting',c_bool),
        ('gain_quant',c_float),
        ('gain_quant_s',c_int16),
        ('decode',CFUNCTYPE(c_int,c_void_p,POINTER(c_uint8),POINTER(c_uint8),c_uint32)),
        ('decode_f',CFUNCTYPE(c_int,c_void_p,POINTER(c_float),POINTER(c_uint8),c_uint32)),
        ('free',CFUNCTYPE(None,c_void_p)),
        ('tmp',POINTER(c_uint8)),
        ('symbols_uc',POINTER(c_uint8))]

viterbi_t = srslte_viterbi_t()

在实例化时,ctypes对结构进行零初始化。

结构中的解码行是函数指针。 CFUNCTYPE用于定义函数指针返回类型和参数。