Wednesday, June 29, 2011

Using a shared library written in C with Python

I'm trying to combine some C and Python. Did some "light" reading on the ctypes module in Python.

There are several ways of using C libraries in Python. Ctypes, SWIG, Cython, and plain making a Python module in C. Ctypes seemed the most straightforward.

Ok, to start with I needed a library. I jumped into Ubuntu and started a new shared library project in CodeBlocks and did the following:

This compiles to a .so file. I named the project sayhello so it compiled libsayhello.so. I put this file in /user/lib.
Alrighty so I have my library. Time to get into Python. I don't have any Python IDE so I just use the terminal. I want to use Python to call my sayhello() function.

And there you have it - a VERY simple example of calling a C function in Python.
There is a lot about shared libraries I don't understand. I have a superficial knowledge of what's happening behind the scenes (and I know what the benefits of using dynamic link libraries are). I keep reading things about "exporting" or "importing" functions but I'm not sure what that means, and I don't understand some of the stuff I see in Windows .dll source code.

Aaaanyway. I've been up since 6am on this and I am done thinking about this for today.

No comments:

Post a Comment