Python ctypes return values question

Emilio picture Emilio · May 20, 2011 · Viewed 8.5k times · Source

Why if i have this simple code

void voidFunct() {
      printf("voidFunct called!!!\n");
}

I compile it as a dynamic library with

gcc -c LSB.c -o LSB.o 
gcc -shared -Wl -o libLSB.so.1 LSB.o 

And i call function from a python interpreter, using ctypes

>>> from ctypes import *
>>> dll = CDLL("./libLSB.so.1")
>>> return = dll.voidFunct()
voidFunct called!!!
>>> print return
17

why the value returned from a void method is 17 and not None or similar? Thank you.

Answer

Boaz Yaniv picture Boaz Yaniv · May 20, 2011

From the docs:

class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

Instances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are assumed to return int.

In short, you defined voidFunct() as a functioning returning int, not void, and Python expects it to return an int (which it gets, somehow, anyway - it's just happen to be a random value).

What you should probably do, is to explicitly state a return value type of None.

dll.voidFunct.restype = None