【问题标题】:How to determine Python3 ctypes .argtypes from C function signature?如何从 C 函数签名中确定 Python3 ctypes .argtypes?
【发布时间】:2021-04-27 23:15:15
【问题描述】:

我正在为第 3 方 DLL 编写 ctypes 接口(我无法控制 DLL)。

我的代码似乎可以工作,但我担心我设置 .argtypes 错误。

我试图调用的 C 函数的签名是:

int GetData(unsigned short option, unsigned char* buffer, int bufferLength, int &actualLength);

option 表示请求的数据类型,buffer 指向我提供的缓冲区,bufferLength 是缓冲区的长度(以字节为单位)。

DLL 函数写入缓冲区,并将它实际写入的字节数放入actualLength

我的代码:

import ctypes

dll = ctypes.CDLL("dll_name.dll")

def GetData(option):

    BUFSIZE = 6

    buf = bytearray(BUFSIZE)

    ptr_to_buf = (ctypes.c_char*len(buf)).from_buffer(buf)

    actualLength = ctypes.c_int()

    dll.GetData.argtypes = (ctypes.c_ushort, 
                            ctypes.c_char_p, 
                            ctypes.c_int, 
                            ctypes.POINTER(ctypes.c_int))

    dll.GetData.restype = int

    dll.GetData(option, 
                ptr_to_buf, 
                BUFSIZE, 
                ctypes.byref(actualLength))

    return (buf, actualLength.value)

GetData() 的调用是否准确反映了.argtypes?

  1. 可以像我在这里所做的那样将ptr_to_buf 作为ctypes.c_char_p 传递吗?
  2. 可以像我在这里所做的那样将ctypes.byref 传递到ctypes.POINTER 吗?
  3. 什么时候需要使用.pointer 而不是.byref? 我确实阅读了ctype 文档,我知道他们说.byref 更快,但我不清楚何时需要.pointer
  4. 还有什么我做错了吗?

【问题讨论】:

  • 这一切都很好。用c_void_p代替c_char_p可能会更自然一些,但是净效果应该是一样的,所以我就不去碰了。

标签: python python-3.x ctypes


【解决方案1】:

.argtypes 很好。您可能希望POINTER(c_ubyte) 完全同意原型,但通常c_char_p 更容易使用。

  1. 可以像我在这里所做的那样将 ptr_to_buf 作为 ctypes.c_char_p 传递吗?

是的。数组作为相同元素类型的指针传递。

  1. 可以像我在这里所做的那样将 ctypes.byref 传递给 ctypes.POINTER 吗?

是的。

  1. 什么时候需要使用 .pointer 而不是 .byref?我确实阅读了 ctype 文档,我知道他们说 .byref 更快,但我不清楚何时需要 .pointer。

当你需要一个具体的指针时创建一个pointer。我很少使用pointer。假设你有这段 C 代码并且有一些理由模仿它:

int x = 5;
int* y = &x;

Python 等价物是:

x = c_int(5)
y = pointer(x)
  1. 还有什么我做错了吗?

.restype 应该有一个 ctype 类型。 .restype = c_int 是正确的。

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2018-08-19
    • 2023-01-30
    • 2021-07-21
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多