문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top