在 Python 中创建 C 函数指针结构

Create C function pointers structure in Python

我正在 Python 2.7 中编写框架,它将提供测试 C 编写的 APIs 的功能。我有 DLL 和 C 源代码本身。问题是一些 C API 函数需要作为回调函数的输入结构,我找不到如何在 Python 中创建结构的方法,哪些字段是C 函数指针。我知道如何使用 ctypes 在 Python 中创建回调函数,但我需要将这些回调打包到 C 结构中以传递给 C API。代码中的所有这些看起来像这样:

C 函数指针和 C 结构:

#define DRIVERCALLAPI
typedef void*( DRIVERCALLAPI *fn_DRV_COMM_Open )(void*);
typedef void(DRIVERCALLAPI *fn_DRV_COMM_Close)(void*);
typedef int(DRIVERCALLAPI *fn_DRV_COMM_Transfer)(void *, unsigned char *, int);

typedef struct DriverCallbacks_t
{
    fn_DRV_COMM_Open                drvcomm_Open;
    fn_DRV_COMM_Close               drvcomm_Close;
    fn_DRV_COMM_Transfer            drvcomm_Transfer;
} DriverCallbacks;

typedef struct InitDataEntry_t
{
    char iface[64];
    void* handle;
} InitDataEntry;

其中 handle 指向 DriverCallbacks 的一个对象。

typedef struct InitDataContainer_t
{
    uint32_t size;
    uint32_t id; 
    InitDataEntry* data;
} InitDataContainer;

InitDataContainer 的指针应该传递给 API 函数。

void* dev_Create( void* args )

API 使用适当的函数初始化回调函数,以便稍后使用它们。我需要以某种方式创建 DriverCallbacks InitDataEntryInitDataContainer 的 Python 结构。关于如何实现它的任何提示?提前致谢!

经过多次实验,我终于找到了如何创建 Python 结构,该结构对应于以函数指针作为字段的 C 结构。这个想法是使用 void 指针代替,即 c_void_p 来自 ctypes。对于提供的示例,python 代码为:

from ctypes import *
class DriverCallbacks(Structure):
    _fields_ = [
        ("drvcomm_Open",     c_void_p),
        ("drvcomm_Close",    c_void_p),
        ("drvcomm_Transfer", c_void_p)
    ]

class InitDataEntry(Structure):
    _fields_ = [
        ("iface",   64 * c_byte),
        ("handle",  c_void_p)
    ]

class InitDataContainer(Structure):
    _fields_ = [
        ("size",    c_uint),
        ("id",      c_uint),
        ("data",    POINTER(InitDataEntry))
    ]

对象的创建和库函数调用可能是这样的(它已经过测试并且对我有用):

lib = cdll.LoadLibrary(LIBNAME)

driverFuncList = DriverCallbacks()
driverFuncList.drvcomm_Open = cast(lib.ftdi_open, c_void_p)
driverFuncList.drvcomm_Close = cast(lib.ftdi_close, c_void_p)
driverFuncList.drvcomm_Transfer = cast(lib.ftdi_transfer, c_void_p)

initData = InitDataEntry()
libc = cdll.msvcrt
libc.strcpy(byref(initData.iface), c_char_p("DriverCallbacks"))
initData.handle = cast(pointer(driverFuncList), c_void_p)

initDataCont = InitDataContainer()
initDataCont.size = c_uint(3)
initDataCont.id = c_uint(0)
initDataCont.data = pointer(initData)

ret = lib.dev_Create(byref(initDataCont))

driverFuncList 对象也可以从 C 库中填充,如果有这样的函数设置回调函数指针。