Segfault with ctypes when returning a struct - 32-bit linux

so I get segfault from ctypes on a 32-bit Linux machine, which I cannot play on 64-bit darwin or linux.

Here is C:

typedef struct { void *ptr; } doodle; doodle C_intpointerfunction(int *a) { *a = 41; doodle foo; foo.ptr = a; return foo; } 

which compiled with:

 gcc -c intpointerlibrary.c gcc -shared intpointerlibrary.o -o libintpointerlib.so 

and here is Python:

 import numpy as N from ctypes import * _libintpointer = N.ctypeslib.load_library('libintpointerlib.so','.') _libintpointer.C_intpointerfunction.restype = c_void_p _libintpointer.C_intpointerfunction.argtypes = [POINTER(c_int)] def P_intpointerfunction(): lrc = c_int(0) print "lrc before (should be 0) = "+str(lrc.value) return_val = _libintpointer.C_intpointerfunction(byref(lrc)) print "lrc after (should be 41) = "+str(lrc.value) return return_val 

so now when i call this function:

  rc = P_intpointerfunction() 

I get segfault. I tried to create a Python class to wrap the returned structure created on the C side with the same results. If you return the native ctypes type (e.g. c_int), everything works fine. Is it really just a 32-bit Linux problem or something that I have not considered? Thanks!

+4
source share
1 answer

Not sure why you set restype = c_void_p ;

 class DOODLE(Structure): _fields_ = [('ptr', c_void_p)] _libintpointer.C_intpointerfunction.restype = DOODLE 

works as expected for me on Linux x86-64.

+5
source

Source: https://habr.com/ru/post/1383541/


All Articles