0

I have this weird case where I absolutely need to open a library using ctypes._dlopen (intercepted method that use a weird memory layout) and then so I can use it in a more simpler way (with my header definitions) I need to load the handle (so the buffer) via cffi. Here is the code I have so far, my issue is: How can I pass the handle which is just an int (aka the pointer address) as a void * to cffi without it not screaming about it (remember it needs an object of instance CData)

from cffi import FFI
from ctypes import *
import _cffi_backend
 
ffi = _cffi_backend.FFI()
ctypes_lib = CDLL("./_native__lib.so",mode = RTLD_GLOBAL)
print(ctypes_lib)
handle=ctypes_lib._handle
print(handle)
 
# handle=ctypes.cast(handle, ctypes.POINTER(ffi.CData))
handle=ctypes.cast(handle, ctypes.c_void_p)
print(handle)
lib = ffi.dlopen(handle)

TL;DR: ffi.dlopen(ctype._dlopen('lib.so')._handle)

NOTE: This is done in Python 2.7, so some of the hack in cffi source code will work (but this does not affect the core source of the problem)

For ressources, here is the main paragraph of cffi: (https://cffi.readthedocs.io/en/latest/cdef.html?highlight=dlopen#id11) New in version 1.14: ffi.dlopen(handle): instead of a file path, you can give an already-opened library handle, as a cdata of type void *. Such a call converts this handle into a regular FFI object with the functions and global variables declared by ffi.cdef(). Useful if you have special needs (e.g. you need the GNU extension dlmopen(), which you can itself declare and call using a different ffi object). Note that in this variant, dlclose() is not called automatically if the FFI object is garbage-collected (but you can still call ffi.dlclose() explicitly if needed).

hube
  • 1
  • 3
  • cffi.FFI().dlopen(cffi.FFI().cast("void *", ctypes._dlopen("libc.so"))) – hube Feb 02 '22 at 22:27
  • This comment of yours looks like the solution, is that right? If so, maybe write it as an answer (to your own post) so that your question doesn't look unanswered. – Armin Rigo Feb 03 '22 at 21:37
  • [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/questions/58610333/c-function-called-from-python-via-ctypes-returns-incorrect-value/58611011#58611011) – CristiFati Feb 04 '22 at 21:27

0 Answers0