0
votes

I'm trying to communicate with an oscilloscope using Python via a .dll provided by the manufacturer and Ctypes. I'm a novice to C so I might be missing something obvious, but I can't seem to get the more complicated function calls right.

I have got access to the .dll file and the .h file.

Excerpt from the .h file:

typedef long ScHandle;

...

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

My python code:

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

The function is supposed to return a handle to the oscilloscope but instead I get the error:

ValueError: Procedure probably called with too many arguments (12 bytes in excess)

1

1 Answers

0
votes

According to [Python 3.Docs]: ctypes - Calling functions (emphasis is mine):

...

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.

...

Seems like you're using the wrong calling convention (this error also states that you're running the 32bit Python). To correct it, use:

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

Also, you can shorten addr initialization:

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