Python & Ctypes : Passing a struct to a function as a pointer to get back data

标签 python pointers struct ctypes

我查看了其他答案,但似乎无法让它发挥作用。我试图在 DLL 中调用一个函数来与 SMBus 设备进行通信。此函数接受一个指向结构的指针,该结构具有一个数组作为其字段之一。所以...

在 C 中:

typedef struct _SMB_REQUEST
{
    unsigned char Address;
    unsigned char Command;
    unsigned char BlockLength;
    unsigned char Data[SMB_MAX_DATA_SIZE];
} SMB_REQUEST;

我想我必须在 DLL 填充数据数组时设置地址、命令和 block 长度的值。 需要这个结构的函数把它当作一个指针

SMBUS_API int SmBusReadByte( SMBUS_HANDLE handle, SMB_REQUEST *request );

所以我在 Python 中设置了这样的结构:

class SMB_REQUEST(ctypes.Structure):
    _fields_ = [("Address", c_char),
            ("Command", c_char),
            ("BlockLength", c_char),
            ("Data", type(create_string_buffer(SMB_MAX_DATA_SIZE))]

*注意:我也尝试过 ctypes.c_char*SMB_MAX_DATA_SIZE 作为数据类型*

要将指向这种类型的结构的指针传递给函数,我首先尝试将其初始化如下:

data = create_string_buffer(SMB_MAX_DATA_SIZE)
smb_request = SMB_REQUEST('\x53', \x00', 1, data)

这会响应:

TypeError: expected string or Unicode object, c_char_Array_32 found

如果我尝试省略数据数组,如下所示:

smb_request = SMB_REQUEST('\x53', \x00', 1)

不,错误。 但是,当我尝试将其传递给函数时:

int_response =  smbus_read_byte(smbus_handle, smb_request))

我明白了:

ArgumentError: argument 2: <type 'exceptions.TypeError'>: expected LP_SMB_REQUES
T instance instead of SMB_REQUEST

我尝试将它作为指针传递:

int_response =  smbus_read_byte(smbus_handle, ctypes.POINTER(smb_request))

我得到:

----> 1
      2
      3
      4
      5

TypeError: must be a ctypes type

这是我设置艺术类型的方式:

smbus_read_byte.argtypes = (ctypes.c_void_p, ctypes.POINTER(SMB_REQUEST))

我试过转换,但还是不行。谁能帮我解释一下?

更新:

如果我首先像这样初始化结构:

smb_request = SMB_REQUEST('\xA6', '\x00', chr(1), 'a test string')

然后是引用低音:

int_response =  smbus_receive_byte(smbus_handle, ctypes.byref(smb_request))

我没有错误。但是,当函数应该返回“0”表示成功并且返回非零表示失败时,该函数会返回 -1。检查 smb_request.Data 的值会返回“测试字符串”,因此那里没有变化。 任何关于这里可能发生的事情的建议将不胜感激。

谢谢

更新:

由于我收到了一些关于我的 handle 是否正确的询问,这就是我的使用方法。 DLL 的头文件声明如下:

typedef void *SMBUS_HANDLE;

//
// This function call initializes the SMBus, opens the driver and 
// allocates the resources associated with the SMBus.
// All SMBus API calls are valid 
// after making this call except to re-open the SMBus.
//
SMBUS_API SMBUS_HANDLE OpenSmbus(void);

这就是我在 python 中的做法:

smbus_handle = c_void_p() # NOTE: I have also tried it without this line but same result

open_smbus = CDLL('smbus.dll').OpenSmbus
smbus_handle =  open_smbus()
print 'SMBUS_API SMBUS_HANDLE OpenSmbus(void): ' + str(smbus_handle)

我在调用 smbus_read_byte() 之前调用它。我尝试设置 open_smbus.restype = c_void_p() 但出现错误:TypeError: restype must be a type, a callable, or None

最佳答案

这是一个工作示例。您似乎将错误的类型传递给函数。

测试 DLL 代码(Windows 上的“cl/W4/LD x.c”)

#include <stdio.h>

#define SMBUS_API __declspec(dllexport)
#define SMB_MAX_DATA_SIZE 5

typedef void* SMBUS_HANDLE;

typedef struct _SMB_REQUEST
{
    unsigned char Address;
    unsigned char Command;
    unsigned char BlockLength;
    unsigned char Data[SMB_MAX_DATA_SIZE];
} SMB_REQUEST;

SMBUS_API int SmBusReadByte(SMBUS_HANDLE handle,SMB_REQUEST *request)
{
    unsigned char i;
    for(i = 0; i < request->BlockLength; i++)
        request->Data[i] = i;
    return request->BlockLength;
}

SMBUS_API SMBUS_HANDLE OpenSmbus(void)
{
    return (void*)0x12345678;
}

Python 代码

from ctypes import *
SMB_MAX_DATA_SIZE = 5
ARRAY5 = c_ubyte * SMB_MAX_DATA_SIZE

class SMB_REQUEST(Structure):
    _fields_ = [
        ("Address", c_ubyte),
        ("Command", c_ubyte),
        ("BlockLength", c_ubyte),
        ("Data", ARRAY5)]

smbus_read_byte = CDLL('x').SmBusReadByte
smbus_read_byte.argtypes = [c_void_p,POINTER(SMB_REQUEST)]
smbus_read_byte.restype = c_int
open_smbus = CDLL('x').OpenSmbus
open_smbus.argtypes = []
open_smbus.restype = c_void_p

handle = open_smbus()
print 'handle = %08Xh' % handle

smb_request = SMB_REQUEST(1,2,5)

print 'returned =',smbus_read_byte(handle,byref(smb_request))
print 'Address =',smb_request.Address
print 'Command =',smb_request.Command
print 'BlockLength =',smb_request.BlockLength
for i,b in enumerate(smb_request.Data):
    print 'Data[%d] = %02Xh' % (i,b)

输出

handle = 12345678h
returned = 5
Address = 1
Command = 2
BlockLength = 5
Data[0] = 00h
Data[1] = 01h
Data[2] = 02h
Data[3] = 03h
Data[4] = 04h

关于Python & Ctypes : Passing a struct to a function as a pointer to get back data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4351721/

相关文章:

c - C中访问指针数组值的两种方法

c++ - std::list 的 erase 成员函数是否为所有存储的元素调用析构函数?

python - struct.unpack 导致TypeError :'int' 不支持buffer接口(interface)

python - 如何反序列化 python 打印的字典?

python - Anaconda:在 Windows 上使用 anaconda 发行版运行 pylab 时出现属性错误

Python 对象作为字典列表的列表

xcode - 如何在 Xcode Debugger 中打印 NSString 的地址

c - 在 C90 中将 malloc 用于双指针

c - struct内存分配,内存分配应该是4的倍数

python - 在 OpenGL 中的 3D 模型后面绘制背景视频