0

I am trying to get a response from a dll library in python using the ctypes wrapper. The response of the function should return x and y coordinates as c_short. A relevant snippet of my code is as follows:

ethdll = ctypes.cdll.LoadLibrary('C:\\Users\\jgallacher\\Documents\\Software_Drivers\\RTC4eth V2 Software Release 2021-06-25\\DLL\\RTC4ethDLLx64.dll')
def get_xy_pos(ethdll):
    x = ctypes.c_short()
    y = ctypes.c_short()
    res = ethdll.get_xy_pos(ctypes.byref(x), ctypes.byref(y)) 
    print(res)

However, when I try this definition I get a Nonetype(0) as the return. Can anyone suggest what is wrong with my function call? I've attached the

I've attached a picture showing the response type to this question thread.

Thanks!

Jordan.

get_xy_pos

  • 1
    Well, it's a `void` function - `None` is exactly what you should expect as the result. Take a look at your `x` and `y` parameters. – jasonharper Dec 09 '21 at 03:03
  • Hi Jason, thanks for your reply. If it’s a void how am I meant to retrieve the x and y values from the call? – Jordan Gallacher Dec 09 '21 at 03:43
  • You retrieve them *from the parameters*. – jasonharper Dec 09 '21 at 03:47
  • Could you give me an example of how I might do that? My understanding is that I would need a pointer with an array and then fill that array? – Jordan Gallacher Dec 09 '21 at 05:01
  • `print(x.value, y.value)`. You are passing pointers to these parameters when you call the function, that's what `byref()` does. – jasonharper Dec 09 '21 at 05:05
  • Something seems wrong. With your code only, you should get some *int* value, not *None*. Anyway, check: [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/questions/58610333/c-function-called-from-python-via-ctypes-returns-incorrect-value/58611011#58611011). – CristiFati Dec 09 '21 at 08:31

1 Answers1

0

The function returns void, so capturing the return value does nothing. You have created x and y variables to hold the result and need to inspect them after calling the function. Here's a working example with a sample DLL function implementation:

test.c

__declspec(dllexport)
void get_xy_pos(short *xpos, short *ypos) {
    *xpos = 5;
    *ypos = 7;
}

test.py

import ctypes as ct

dll = ct.CDLL('./test')

# Good practice is to define .argtypes and .restype so ctypes can do type-checking
dll.get_xy_pos.argtypes = ct.POINTER(ct.c_short),ct.POINTER(ct.c_short)
dll.get_xy_pos.restype = None

def get_xy_pos():
    x = ct.c_short() # storage for output parameters
    y = ct.c_short()
    dll.get_xy_pos(ct.byref(x), ct.byref(y)) # pass by reference
    return x.value,y.value  # inspect the return values

print(get_xy_pos())

Output:

(5, 7)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251