3 ms·
How to use C library in python? (Generating Python wrappers for C library)
- jnbiche 15y agoSWIG is cool, but for wrapping an existing library, nothing is easier in Python than ctypes. There's a slight performance hit, but you'll still be getting much better performance than an equivalent library in pure Python. ctypes is so simple to use that I routinely use it on the command line: >>> from ctypes.util import find_library >>> from ctypes import * >>> libcdir = find_library("c") >>> libc = cdll.LoadLibrary(libcdir) >>> libc.strlen("TESTSTRING") 10 The cool thing about the find_library function that I imported from ctypes.util is that it finds the location of any c library that is registered on your system, regardless of platform. It's not 100% reliable, so find_library should be used cautiously on production code (you should really know the library path for production code). But it's great for prototyping. Any c library that comes to mind is as easy to use as find_library("c_library_name").
- dalke 15y agoSWIG can be easier than many cases of using ctypes. One of the examples when SWIG first came out was to wrap the entire OpenGL interface, in a few lines of code. This was possible because the SWIG processor could understand the OpenGL header files and generate interface code with the right number of parameters and type conversion. With ctypes it's still a mostly manual operation. For example, if you want to call libc's "cos" then you'll need to declare the return type, as otherwise it assumes an integer. There are additional advantages to using ctypes. For one, it's portable to Jython, pypy, and IronPython. Also, cython can be easier than ctypes if you need access to any compile-time values, like #define values and other macros.