如何使用ctypes

时间:2015-09-18 13:23:57

标签: python c++ c dll

背景

我在Python中有一些分析软件我必须将一个4096字节的列表(看起来像这个 [80, 56, 49, 50, 229, 55, 55, 0, 77, ......])传递给一个dll,以便dll将它写入设备。

  1. 要写入的字节存储在变量名称数据
  2. 必须从python调用的c函数(在dll中)是

    int _DLL_BUILD_ IO_DataWrite(HANDLE hDevice, unsigned char* p_pBuff, unsigned char p_nByteCntInBuff);

  3. 我无法访问dll代码

  4. 已尝试方法

    我尝试声明数据类型

    data_tx = (ctypes.c_uint8 * len(data))(*data)
    

    并调用函数

    ret = self.sisdll.IO_DataWrite(self.handle, ctypes.byref(data_tx), ctypes.c_uint8(pending_bytes))
    

    问题

    似乎没有错误,但它不起作用。 API调用适用于C和C ++。

    我这样做是否正确。谁能请我帮忙指出错误?

1 个答案:

答案 0 :(得分:5)

您尝试实现的目标可以这样做。

接口头,比如functions.h

#include <stdint.h>
#include "functions_export.h" // Defining FUNCTIONS_API
FUNCTIONS_API int GetSomeData(uint32_t output[32]);

C source,functions.c

#include "functions.h"
int GetSomeData(uint32_t output[32]) {
  output[0] = 37;
}

在python中,你只需编写

import ctypes
hDLL = ctypes.cdll.LoadLibrary("functions.dll")
output = (ctypes.c_uint32 * 32)()
hDLL.GetSomeData(ctypes.byref(output))
print(output[0])

您应该会在屏幕上看到数字37。