【问题标题】:Create C function pointers structure in Python在 Python 中创建 C 函数指针结构
【发布时间】:2017-01-31 09:48:13
【问题描述】:

我正在使用 Python 2.7 编写框架,该框架将提供测试 C 编写的 API 的功能。我有 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 InitDataEntry 和 InitDataContainer 的 Python 结构。关于如何实现的任何提示?提前致谢!

【问题讨论】:

    标签: python ctypes


    【解决方案1】:

    经过多次实验,我终于找到了如何使用函数指针作为字段来创建对应于 C 结构的 Python 结构。这个想法是使用 void 指针,即来自 ctypes 的 c_void_p。对于提供的示例,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 库中填充,如果存在设置回调函数指针的此类函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2013-03-07
      相关资源
      最近更新 更多