Domanda

I have a C program with embedded python code. I have compiled python 2.7.2 from source and linked my program against libpython2.7.a.

Now in my python code I wish to call back functions from other C libraries linked into my C program. I can write a python extension (see Extending Embedded Python in this document). However, ctypes would make this a lot easier and would allow me to use some existing code unchaged.

ctypes is geared towards loading shared libraries and I was wondering if there was a way to 'point' it back to my static program code.

I cannot compile the relevant code into a shared library because my target is iOS and AFAIK shared libraries are forbidden by Apple.

È stato utile?

Soluzione

From Python code, you can create ctypes wrappers for static functions like this:

restype = ctypes.c_int
argtypes = [ctypes.c_int, ctypes.c_double]        # or whatever
functype = ctypes.CFUNCTYPE(restype, *argtypes)
wrapper = functype(address_of_static_function_as_an_int)

You can of course call this (or similar) code from your C code.

Altri suggerimenti

Construct a ctypes value (e.g. ctypes.c_void_p) encapsulating your function pointer and pass it into your Python code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top