Wednesday, August 3, 2011

Exploring ctypes (2)

I used an example from before (here) to make a dylib and then called the functions using ctypes. It seems very easy:

add1.c

int f1(int x) { return x + 1; }


add2.c

int f2(int x) { return x + 2; }



> gcc -g -Wall -c add*.c
> gcc -dynamiclib -current_version 1.0 add*.o -o libadd.dylib
> file libadd.dylib
libadd.dylib: Mach-O 64-bit dynamically linked shared library x86_64



> python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> pre = '/Users/telliott/Desktop'
>>> libadd = ctypes.CDLL(pre + '/libadd.dylib', ctypes.RTLD_GLOBAL)
>>> x = libadd.f1(1)
>>> x
2
>>> y = libadd.f2(x)
>>> y
4
>>>


I guess one question is how to alter / determine the search path for ctypes in loading libraries. libc is in /usr/lib, but libpng is in /usr/X11/lib, as we discussed the other day (here):


>>> libc = ctypes.CDLL('libc.dylib', ctypes.RTLD_GLOBAL)
>>> libpng = ctypes.CDLL('libpng.dylib', ctypes.RTLD_GLOBAL)
Traceback (most recent call last):
File "", line 1, in
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(libpng.dylib, 10): image not found
>>> pre = '/usr/X11/lib/'
>>> libpng = ctypes.CDLL(pre + 'libpng.dylib', ctypes.RTLD_GLOBAL)
>>>



>>> import ctypes.util
>>> ctypes.util.find_library('libpng.dylib')
>>> ctypes.util.find_library('png')
>>> ctypes.util.find_library('AGL')
'/System/Library/Frameworks/AGL.framework/AGL'


Obviously, find_library doesn't search /usr/X11/lib. Wonder if there is a way to tell it what we want?

After we look at Andrew's more sophisticated examples, we'll try something relevant to bioinformatics