无法设置 CDLL 函数的 restype:ctypes

问题描述 投票:0回答:1

假设我有一个 C++ dll。我有一个函数 GET_LAST_MESSAGE,它返回 char*。我无法使用 python 从中获取消息,因为 python 假设该函数返回 long int。

这是我的代码:

import ctypes
mydll = ctypes.CDLL(libName)
mydll.['GET_LAST_MESSAGE'].argtypes = None
mydll.['GET_LAST_MESSAGE'].restype = ctypes.c_char_p
message = mydll.['GET_LAST_MESSAGE']()

当我跟踪这段代码时,我发现变量

mydll.['GET_LAST_MESSAGE'].restype
的实际状态保持不变(
ctypes.c_long

但是,以下代码可以按预期工作:

import ctypes
mydll = ctypes.CDLL(libName)
mydll.GET_LAST_MESSAGE.restype = ctypes.c_char_p
mydll.GET_LAST_MESSAGE.argtypes = None
message = mydll.GET_LAST_MESSAGE()

我想编写一个类结构来处理cdll,因此能够加载任意函数对我来说至关重要。这就是为什么我不能使用第二个代码块。 有没有办法指定任意函数的restype?

python dll ctypes
1个回答
0
投票

我想你仍然可以在提供字符串时使用“属性”方式(你不太清楚问题是什么,但我猜这是因为如果你有一个变量

s="GET_LAST_MESSAGE"
,而不是文字字符串常量
"GET_LAST_MESSAGE"
,那么你可以
mydll[s].restype=...
但不能
mydll.s.restype=...

在你提出问题之前我并不知道这一点,但显然

["..."]
为你提供了原始的
restype
,并且没有改变。 即使你

mydll.GET_LAST_MESSAGE.restype = ctypes.c_char_p
mydll['GET_LAST_MESSAGE'].restype

保持不变,而

mydll.GET_LAST_MESSAGE.restype

所以,让我们使用

.
表示法,同时仍然使用字符串参数来指定属性名称

s="GET_LAST_MESSAGE"
mydll.__getattr__(s).restype = ctypes.c_char_p
© www.soinside.com 2019 - 2024. All rights reserved.