【问题标题】:How to pass a python list to C function (dll) using ctypes如何使用 ctypes 将 python 列表传递给 C 函数(dll)
【发布时间】:2015-12-15 16:05:54
【问题描述】:

背景

我有一些 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 代码

方法尝试

我试图声明一个数据类型

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++。

我这样做对吗?任何人都可以请为我指出错误吗?

【问题讨论】:

  • 您是否尝试过定义参数类型:IO_DataWrite.argtypes = [c_void_p, POINTER(c_uint8), c_uint8]
  • 通常,我会使用data_tx = (ctypes.c_uint8 * len(data))(),然后将数据复制到数组中并使用ctypes.byref 调用库。你可以试试这个而不是从数据构造你的数组
  • @JensMunk 把它变成一个答案,这是正确的答案
  • @zwol 我今天晚些时候会这样做。离开一段时间了
  • @JensMunk 请将其转换为答案。正确!!!!!!

标签: python c++ c dll


【解决方案1】:

你试图达到的目标可以这样完成。

接口头,比如functions.h

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

C 源代码,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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    相关资源
    最近更新 更多