[Numpy-discussion] ctypes: how does load_library work ?

David Cournapeau david at ar.media.kyoto-u.ac.jp
Thu Aug 17 23:54:44 CDT 2006


    I am investigating the use of ctypes to write C extensions for 
numpy/scipy. First, thank you for the wiki, it makes it easy to 
implement in a few minutes a wrapper for a C function taking arrays as 
    I am running recent SVN version of numpy and scipy, and I couldn't 
make load_library work as I expected: Let's say I have a  libhello.so 
library on linux, which contains the C function int sum(const int* in, 
size_t n). To wrap it, I use:

import numpy as N
from ctypes import cdll, POINTER, c_int, c_uint

_hello = cdll.LoadLibrary('libhello.so')

_hello.sum.restype    = c_int
_hello.sum.artype     = [POINTER(c_int), c_uint]

def sum(data):
    return _hello.sum(data.ctypes.data_as(POINTER(c_int)), len(data))

n       = 10
data    = N.arange(n)

print data
print "sum(data) is " + str(sum(data))

That works OK, but to avoid the platform dependency, I would like to use 
load_library from numpy: I just replace the cdll.LoadLibrary by :

_hello = N.ctypeslib.load_library('hello', '.')

which does not work. The python interpreter returns a strange error 
message, because it says hello.so.so is not found, and it is looking for 
the library in the directory usr/$(PWD), which does not make sense to 
me. Is it a bug, or am I just not understanding how to use the 
load_library function ?


More information about the Numpy-discussion mailing list