【问题标题】:Return handle from .dll called using Python ctypes从使用 Python ctypes 调用的 .dll 中返回句柄
【发布时间】:2019-09-10 21:21:04
【问题描述】:

我正在尝试通过制造商和 Ctypes 提供的 .dll 使用 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 个字节)

【问题讨论】:

    标签: python dll ctypes


    【解决方案1】:

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

    ...

    当您使用 cdecl 调用约定调用 stdcall 函数时会引发相同的异常,反之亦然

    >>> 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)
    >>>
    

    要找出正确的调用约定,您必须查看 C 头文件或要调用的函数的文档。

    ...

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

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

    另外,你可以缩短 addr 初始化:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多