Ptyon ctypes returns the value of the question

Why if i have this simple code

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

I will 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 the function from the python interpreter using ctypes

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

why is the value returned by the void method equal to 17 , and not None or the like? Thanks.

+4
source share
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 expected 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 somehow gets, this is just a random value).

What you probably should do is explicitly specify the return type of None .

 dll.voidFunct.restype = None 
+16
source

This behavior is undefined. You ask ctypes to read the return value, which is simply not there. He reads something from the stack, but what returns is poorly defined.

+5
source

All Articles