使用Python ctypes调用的.dll返回句柄

2024-04-20 01:37:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过制造商提供的.dll和Ctypes使用Python与示波器进行通信。我是C的新手,所以我可能遗漏了一些明显的东西,但我似乎无法正确地调用更复杂的函数。你知道吗

我有权访问.dll文件和.h文件。你知道吗

节选自.h文件:

typedef long ScHandle;

...

int ScOpenInstrument(int wire, char* address, ScHandle* rHndl);

我的python代码:

import ctypes

lib = ctypes.WinDLL("ScAPI.dll")

# Define types
ScHandle = ctypes.c_long

# Define function argument types
lib.ScOpenInstrument.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ScHandle)]
lib.ScStart.argtypes = [ScHandle]

# Init library
ret = lib.ScInit()

# Open instrument
wire = ctypes.c_int(7)
addr = ctypes.c_char_p("91SB21329".encode("utf-8"))
handle = ScHandle(0)

ret = lib.ScOpenInstrument(wire, addr, ctypes.byref(handle))

该函数应该返回示波器的句柄,但我得到的却是错误:

ValueError:调用过程的参数可能太多(超过12字节)


Tags: 文件函数libctypeslonginttypesdll
1条回答
网友
1楼 · 发布于 2024-04-20 01:37:02

根据[Python 3.Docs]: ctypes - Calling functions强调是我的):

...

The same exception is raised when you call an stdcall function with the cdecl calling convention, or vice versa:

>>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>

To find out the correct calling convention you have to look into the C header file or the documentation for the function you want to call.

...

似乎您使用了错误的调用约定(此错误还表示您正在运行32位Python)。要更正它,请使用:

lib = ctypes.CDLL("ScAPI.dll")

此外,您还可以缩短地址初始化:

addr = ctypes.c_char_p(b"91SB21329")

相关问题 更多 >