gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:08:22 24 4
gpt4 key购买 nike

在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(设备数量)相对应的数组。

有什么想法可以解决这个问题吗?

非常感谢您的帮助!!!

最佳答案

使用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

关于python 使用 ctypes 处理 dll - 结构 OUT 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7017107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com