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.

Avner
  • 5,791
  • 2
  • 29
  • 33

2 Answers2

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • For some reason this crashes my (static) libffi in _ctypes. – Avner Jun 13 '12 at 14:01
  • @Avner: Honestly, I did not actually *try* the above code, so I can't help you with that crash. – Sven Marnach Jun 13 '12 at 14:05
  • 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. – Avner Jun 13 '12 at 20:17
0

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

ecatmur
  • 152,476
  • 27
  • 293
  • 366