python - 使用 Python Ctypes 将结构指针传递给 DLL 函数

标签 python pointers struct ctypes

我正在尝试使用 Python ctypes 访问 DLL 文件中的函数。提供的功能说明如下。

Prototype: Picam_ConnectDemoCamera( PicamModel model,
                                    const pichar* serial_number,
                                    PicamCameraID* id )

Description: Virtually connects the software-simulated 'model' with 'serial_number'
and returns the camera id in `_id_`
Notes: `_id_` is optional and can be null

该函数引用了 DLL 中定义的一些变量类型。接下来描述这些变量

PicamModel
Type: enum
Description: The camera model.

PicamCameraID
Type: Struct
- PicamModel model: _model_ is the camera model
- PicamComputerInterface computer_interface: computer_interface is the method of
communication
- pichar sensor_name [PicamStringSize_SensorName]: sensor_name contains the name of
the sensor in the camera
- pichar serial_number [PicamStringSize_SerialNumber]: serial_number contains the
unique serial number of the camera

注意'pichar'在其中一个提供的头文件中定义如下:

typedef          char   pichar; /* character native to platform   

这看起来很简单,但出于某种原因对我来说并不适用。

我的理解是这样的:我给函数传了三个变量:

1) 模型,它实际上是一个enum。有人告诉我 python ctypes 本身并不支持枚举,所以我将一个整数 2 传递给它,它映射到一个特定的模型类型。

2) 指向序列号的指针(我可以弥补:任意字符串)

3) 指向PicamCameraID 的指针,一个在DLL 中定义的变量类型,基于struct 类型

通读 SO 后,我找到了一些不错的起点,但我的运气仍然不佳。这是我迄今为止最好的一张照片

def pointer(x):
      PointerToType = ctypes.POINTER(type(x))
      ptr = ctypes.cast(ctypes.addressof(x), PointerToType)
      return ptr

class PicamCameraID(ctypes.Structure):
      pass
PicamCameraID._fields_=[("model",ctypes.c_int),
                    ("computer_interface",ctypes.c_int),
                    ("sensor_name",ctypes.c_char_p),
                    ("serial_number",ctypes.c_char_p)]

myid = PicamCameraID()
model = ctypes.c_int(2)
serialnum = ctypes.c_char_p('asdf')
print picam.Picam_ConnectDemoCamera(model, pointer(serialnum), ctypes.byref(myid))

如您所见,我正在尝试创建与 DLL 中定义的 PicamCameraID 结构相对应的变量类型。我的直觉是在将参数传递给函数时使用 ctypes.pointer 命令来引用它,但我发现指示使用 ctypes.byref 代替 elsewhere .

代码运行没有错误(返回 0),但是,当我尝试访问结构 PicamCameraID 的属性时,我得到了不同的结果:

myid.model 返回“2”,这很好,这就是我指定的 myid.computer_interface 返回正常的“1”

但是 问题是 myid.serial_number 返回

Traceback (most recent call last):   File "<pyshell#28>", line 1, in
<module>
   myid.serial_number ValueError: invalid string pointer 0x2820303031207820

myid.sensor_name返回:

Traceback (most recent call last):   File "<pyshell#29>", line 1, in
<module>
    myid.sensor_name ValueError: invalid string pointer 0x3034333120563245

出于某种原因,这些字符串没有被正确填充?

任何想法将不胜感激,我是 python ctypes(和 c)的新手

亲切的问候

2013 年 6 月 1 日添加

typedef enum PicamStringSize {
    PicamStringSize_SensorName     =  64,
    PicamStringSize_SerialNumber   =  64,
    PicamStringSize_FirmwareName   =  64,
    PicamStringSize_FirmwareDetail = 256 } PicamStringSize; 

typedef struct PicamCameraID {
    PicamModel             model;
    PicamComputerInterface computer_interface;
    pichar                 sensor_name[PicamStringSize_SensorName];
    pichar                 serial_number[PicamStringSize_SerialNumber];
} PicamCameraID;

最佳答案

您对 PicamCameraID 结构的定义不正确:sensor_nameserial_numberarrays :

"""
struct PicamCameraID {
  PicamModel             model;
  PicamComputerInterface computer_interface;
  pichar                 sensor_name[PicamStringSize_SensorName];
  pichar                 serial_number[PicamStringSize_SerialNumber]; 
};
"""
import ctypes as c

PicamStringSize_SensorName = PicamStringSize_SerialNumber = 64
PicamModel = PicamComputerInterface = c.c_int
pichar = c.c_char

class PicamCameraID(c.Structure):
    _fields_ = [("model", PicamModel),
                ("computer_interface", PicamComputerInterface),
                ("sensor_name", pichar * PicamStringSize_SensorName),
                ("serial_number", pichar * PicamStringSize_SerialNumber)]

似乎第二个参数只是一个字符串,因此您不需要对其应用 pointer()。这是 Picam_ConnectDemoCamera() 函数的 ctypes 原型(prototype):

"""
Picam_ConnectDemoCamera(PicamModel model, const pichar* serial_number,
                        PicamCameraID* id)
"""
pichar_p = c.c_char_p # assume '\0'-terminated C strings
Picam_ConnectDemoCamera.argtypes = [PicamModel, pichar_p,
                                    c.POINTER(PicamCameraID)]
Picam_ConnectDemoCamera.restype = c.c_int # assume it returns C int

调用它:

picam_id = PicamCameraID()
rc = Picam_ConnectDemoCamera(2, "serial number here", c.byref(picam_id))
print(rc)
print(picam_id.sensor_name.value) # C string
print(picam_id.sensor_name.raw)   # raw memory

关于python - 使用 Python Ctypes 将结构指针传递给 DLL 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16867670/

相关文章:

单独头文件中的 C++ 结构原型(prototype)

python Pandas : groupby one level of MultiIndex but remain other levels instead

python - PyFacebook 无限 session

python - Sphinx meth 角色不创建链接

c++ - char 数组作为 placement new 的存储

c - 复合/字符串文字存储在内存中的什么位置?

c - 从文件填充结构数组

python - 按值排序后如何按字母顺序对字典的键进行排序?

pointers - 如何在go中获取函数的地址?

python - struct.pack(f'{len(x)}s', x) 有什么作用吗?