Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes return values question

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.

like image 618
Emilio Avatar asked May 20 '11 14:05

Emilio


2 Answers

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
like image 164
Boaz Yaniv Avatar answered Oct 21 '22 02:10

Boaz Yaniv


That's undefined behaviour. You are asking ctypes to read a return value that is simply not there. It reads something off the stack, but what comes back is ill-defined.

like image 7
David Heffernan Avatar answered Oct 21 '22 03:10

David Heffernan