Skip to content Skip to sidebar Skip to footer

Combining Ctypes And Swig

I have been using SWIG for a long time - generally I like it. But doing callback functions seems (much) easier using ctypes. How can I combine the two 'ways' of interacting with a

Solution 1:

If x.pyd is the swig compiled extension module, then you can load the dll via ctypes in this way:

import x
from ctypes importPyDLLdll= PyDLL(x.__file__)

Depending on the calling conventions used by the exported functions, you may need to use PyDLL, WinDLL, or CDLL.

Solution 2:

The Buffer Protocol may be your best bet ( http://docs.python.org/c-api/buffer.html ).

From C code (eg swig generated code) you can get the pointer to the underlying C data by accessing this interface.

Watch out there are two versions of the buffer interface, ctypes objects in python 2.x will expose the old protocol, in python 3.x they expose the new one.

You will have to go down to the Python C API level, but only once if you wrap everything up nicely - eg maybe make an %inline function returning a void* for anything supporting a buffer protocol, and use that in typemaps for your callback types.

Post a Comment for "Combining Ctypes And Swig"