[SciPy-user] Using ctypes and scipy

Travis Oliphant oliphant at ee.byu.edu
Tue Nov 22 20:45:56 CST 2005


I'm including a (small) section in my book on the use of ctypes with 
scipy.   But, I wanted to let users know a little bit of how nifty it 
can be for calling out to an external compiled-library.  Ctypes is an 
additional Python module downloaded separately ( see 
http://starship.python.net/crew/theller/ctypes/ )

Be warned, however, that calling C-code directly like this can easily 
result in segfaults if you make a mistake in calling the external 
library.  But it is a quick-and-dirty way to access arbitrary library code.

Consider the C-code in a file called simple.c:

int
addone(double *ptr, int size)
{
    int k;

    for (k=0; k<size; k++) *ptr++ += 1;
}

int
makeone(double *ptr, int size)
{
    int k;
    for (k=0; k<size; k++) *ptr++ = 1;
}

Suppose this is compiled into a library (on my Linux system I do this
with the command "gcc -shared -o simple.so simple.c")

Now you can load and call these functions from within Python:

from ctypes import cdll, c_int, c_void_p
from scipy import empty

N = 1000
a = empty(N,dtype=float)

lib = cdll.LoadLibrary('./simple.so') 
# this may be called simple.so or simple.<zzz> where
# <zzz> is the extension for shared libraries on your system.

# Create c-types arguments to pass
cN = c_int(N)
# This is a pointer to the actual location of the data
ptr = c_void_p(int(a.__array_data__[0], 0)) 

#Now call the routines
num = lib.makeone(ptr, cN)
num = lib.addone(ptr, cN)
print a[:10]


Output is:

[ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]

Kind of nifty, no?

-Travis













More information about the SciPy-user mailing list