4

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

For some reason this crashes my (static) libffi in _ctypes.
@Avner: Honestly, I did not actually try the above code, so I can't help you with that crash.
The code looks right (this is why I accepted your answer). I suspect the problem is with the porting of libffi to iOS and the way I compiled libpython.a (with static modules, static _ctypes and static libffi). But since I did not yet solve this crash, this remains a suspicion for now.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.