Calling C functions inside Python
January 25, 2009
In my current work, I’m developing new ways to test a Telecom framework. Firstly, I was building automation tests with cgreen to blackbox/unit test model. But the development stages were going a little more slow than I thought because write and debug C code is not so easy.
Suddenly, I though…”Hey, why do I not build these tests with python scripts ???”. And my response was: “Ctypes is your friend!”
Ctypes permits you call C functions inside python code. It’s wonderful. Let’s see how to do it in OpenSolaris environment:
First, download ctypes:
$ wget -c \ http://ufpr.dl.sourceforge.net/sourceforge/ctypes/ctypes-1.0.2.tar.gz
Install ctypes in a local path (as normal user):
$ tar -zxvf ctypes-1.0.2.tar.gz
$ cd ctypes-1.0.2
$ python setup.py install --prefix=$HOME/python
Export your PYTHONPATH environment variable:
$ export PYTHONPATH=$HOME/python/lib/python2.4/site-packages
Testing ctypes:
$ python
>>> import ctypes
OK ! Ctypes is there, but how do I use it ???
See a little example that I made to explain how to use ctypes:
- A file named test.c with a function (sum) that returns a sum of two values:
int sum (int a, int b)
{
return (a+b);
}
- Compile it as a shared library:
$ gcc -fPIC -c test.c
$ gcc -shared -o test.o libtest.so
- Make sure that our library will be found
$ cp test.so $HOME/example
$ export LD_LIBRARY_PATH=$HOME/example
- Let’s call the function sum through a Python script
$ python
>>> from ctypes import *
>>> cdll.LoadLibrary('libtest.so')
<CDLL 'libtest.so', handle fe7806e0 at 80dfcec>
>>> libc = CDLL('libtest.so')
>>> libc.sum()
112710980
>>> libc.sum(1,2)
3
I can see a smile in your face. Yeah! Ctypes is a great trick to C programmers
Enjoy it!
Useful links:
- http://docs.python.org/library/ctypes.html

Enabling a Marvel Yukon NIC on OpenSolaris
January 11, 2009
When I installed OpenSolaris 2008.05 in my laptop (Sony Vaio), the operating system does not recognized my ethernet card (marvel yukon), but identified my wireless NIC.
I don’t use ethernet card frequently because I have a Wireless Access Point. But, some days ago I had to enable my Marvel Yukon.
Let’s see how did I do this:
By default, snv_86 build does not come with the Marvel Yukon driver enabled in the kernel. But you can download it at:
http://homepage2.nifty.com/mrym3/taiyodo/myk-2.6.5.tar.gz
Done that, I take these steps:
-
tar -zxvf myk-2.6.5.tar.gz
-
cd myk-2.6.5
-
rm -Rf obj Makefile
-
ln -s Makefile.i386_gcc Makefile
-
ln -s i386 obj
-
export PATH=/usr/ccs/bin:$PATH
-
which gcc (/usr/ccs/bin/gcc expected)
-
which make (/usr/ccs/bin/make expected)
-
pfexec make install
-
pfexec ./adddrv.sh (should says ok!)
-
ifconfig myk0 plumb
-
ifconfig -a (wow ! I see my ethernet card!!!
)
PS: Before try my tips, please, read the installation document in tarball ’cause you can have to do different steps.
Links:







