What I want to do is the opposite of what most people want to do: I have a library written in Python, and I want to make it available to C (and possibly other languages).
I know that the typical answer to this is using the Python library for C, that is:
#include <Python.h>
int
main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
(source: http://docs.python.org/extending/embedding.html#very-high-level-embedding)
However, this seems less than optimal to me:
What I want, instead, is a way to bind my library to LOT of languages, including C. I don't care about automatic wrapper generation: my library is quite simple, so I can write glue code.
At the moment, the only solution I came up with is using code similar to the one above to bind my library to C. Then use SWIG to bind the C library to other languages.
Is there a better one?
There a number of ways to do this. The rawest, simplest way is to use the Python C API and write a wrapper for your C library which can be called from Python. This ties your module to CPython. The second way is to use ctypes which is an FFI for Python that allows you to load and call functions in C libraries directly.
Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.
To write Python modules in C, you'll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code. All of these tools and more are collectively bundled in the Python. h header file.
For example, Python bindings are used when an extant C library, written for some purpose, is to be used from Python. Another example is libsvn which is written in C to provide an API to access the Subversion software repository.
Well C is the Lingua franca of programming. So I would say your approach is correct. Create a binding for C and than use tools like SWIG and the FFI of the other Languages to bind to C.
Only one other idea comes to mind. Today we see HTTP emerging as a new Lingua franca for all kind of APIs and Interfaces. So one could think about creating a little webservice written in python offering some REST interface. But clearly this only makes sense in certain settings.
Of course, once you decide to run your python lib in a separate process there are all the possibilities of inter process communication like named pipes or sockets and toolkits like Apache Thrift, Google Protocol Buffers or 0MQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With