I am using ctypes to wrap a C-library (which I have control over) with Python. I want to wrap a C-function with declaration:
int fread_int( FILE * stream );
Now; I would like to open file in python, and then use the Python file-object (in some way??) to get access to the underlying FILE * object and pass that to the C-function:
# Python
fileH = open( file , "r")
value = ctypes_function_fread_int( ????? )
fileH.close()
Is the Python file <-> FILE * mapping at all possible?
Joakim
A Python file object does not necessarily have an underlying C-level FILE *
-- at least, not unless you're willing to tie your code to extremely specific Python versions and platforms.
What I would recommend instead is using the Python file object's fileno
to get a file descriptor, then use ctypes
to call the C runtime library's fdopen
to make a FILE *
out of that. This is a very portable approach (and you can go the other way, too). The big issue is that buffering will be separate for the two objects opened on the same file descriptor (the Python file object, and the C FILE *
), so be sure to flush said objects as often as needed (or, open both as unbuffered, if that's more convenient and compatible with your intended use).
If you want to use stdout
/stdin
/stderr
, you can import those variables from the standard C library.
libc = ctypes.cdll.LoadLibrary('libc.so.6')
cstdout = ctypes.c_void_p.in_dll(libc, 'stdout')
Or, if you want to avoid using void*
for some reason:
class FILE(ctypes.Structure):
pass
FILE_p = ctypes.POINTER(FILE)
libc = ctypes.cdll.LoadLibrary('libc.so.6')
cstdout = FILE_p.in_dll(libc, 'stdout')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With