cytpes definition for Handle
I am working with a library written in C that has a function which returns a handle (to an object I expect). I have tried a number of different ctypes for this handle, but each time I try to use the handle in the next function I get a Seg Fault. What is the correct way to define (and use) a handle (I have seen examples for Windows, but I'm developing for Linux and MacOS)?
Example Python Code:
Provided_Lib = "../libProvided.so"
libc = CDLL(Provided_Lib)
DSHandle = libc.DevInitialze(config1, config2, err_no)
# The line above is modified from the actual to simplify, it does work correctly
# - if I modify an input it provides he correct error codes.
#This line causes the Seg Dump:
return_code = libc.DevReset(DSHandle)
C-Code definitions:
INT DevReset(HANDLE hDSer);
#ifndef HANDLE
#define HANDLE VOID*
#endif
Declare appropriate .argtypes
and .restype
. Without them, ctypes
assumes all parameters are c_int
or pointers and the return type is c_int
(32-bit). Since pointers are typically 64-bit on modern OSes the 64-bit handle gets truncated to 32 bits without a proper .restype
. For example:
from ctypes import *
Provided_Lib = "../libProvided.so"
libc = CDLL(Provided_Lib)
libc.DevInitialize.argtypes = # put tuple of argument types here...not provided
libc.DevInitialize.restype = c_void_p # appropriate for a C void*
libc.DevReset.argtypes = c_void_p
libc.DevReset.restype = c_int # or whatever...not provided.
DSHandle = libc.DevInitialize(config1, config2, err_no)
return_code = libc.DevReset(DSHandle)