python使用ctypes来处理dll - 结构OUT参数

时间:2011-08-10 20:10:27

标签: python dll ctypes

在dll的头文件中,我有以下结构

typedef struct USMC_Devices_st{
DWORD NOD;          // Number of the devices ready to work

char **Serial;      // Array of 16 byte ASCII strings
char **Version;     // Array of 4 byte ASCII strings
} USMC_Devices;         // Structure representing connected devices

我想调用一个dll函数: DWORD USMC_Init(USMC_Devices& Str);

我试过这个:

class USMCDevices(Structure):
   _fields_ = [("NOD", c_long),
            ("Serial", c_char_p),
            ("Version", c_char_p)]

usmc = cdll.USMCDLL #this is the dll file
init = usmc.USMC_Init
init.restype = c_int32; # return type
init.argtypes = [USMCDevices]; # argument
dev = USMCDevices()
init(dev)

我在这里收到错误。我猜问题是“Serial”和“Version”,它们都是与NOD(设备数量)对应的数组。

任何想法如何解决这个问题?

我真的很感谢你的帮助!!!

1 个答案:

答案 0 :(得分:2)

POINTER(c_char_p)指针使用char **。索引SerialVersion为给定的以null结尾的字符串创建Python字符串。请注意,超出NOD - 1的数组中的索引会产生垃圾值,或者会使解释器崩溃。

C:

 
#include <windows.h>

typedef struct USMC_Devices_st {
    DWORD NOD;       // Number of the devices ready to work
    char **Serial;   // Array of 16 byte ASCII strings
    char **Version;  // Array of 4 byte ASCII strings
} USMC_Devices;

char *Serial[] = {"000000000000001", "000000000000002"};
char *Version[] = {"001", "002"};

__declspec(dllexport) DWORD USMC_Init(USMC_Devices *devices) {

    devices->NOD = 2;
    devices->Serial = Serial;
    devices->Version = Version;

    return 0;
}

// build: cl usmcdll.c /LD

的Python:

 
import ctypes
from ctypes import wintypes

class USMCDevices(ctypes.Structure):
    _fields_ = [("NOD", wintypes.DWORD),
                ("Serial", ctypes.POINTER(ctypes.c_char_p)),
                ("Version", ctypes.POINTER(ctypes.c_char_p))]

usmc = ctypes.cdll.USMCDLL
init = usmc.USMC_Init
init.restype = wintypes.DWORD
init.argtypes = [ctypes.POINTER(USMCDevices)]
dev = USMCDevices()
init(ctypes.byref(dev))

devices = [dev.Serial[i] + b':' + dev.Version[i]
           for i in range(dev.NOD)]
print('\n'.join(d.decode('ascii') for d in devices))

输出:

 
000000000000001:001
000000000000002:002