views:

45

answers:

2

I have a C++ library repeater.so that I can load from Python in Linux the following way:

import numpy as np                                    
repeater = np.ctypeslib.load_library('librepeater.so', '.')

However, when I compile the same library on Mac OS X (Snow Leopard, 32 bit) and get repeater.dylib, and then run the following in Python:

import numpy as np                                
repeater = np.ctypeslib.load_library('librepeater.dylib', '.')

I get the following error:

OSError: dlopen(/mydir/librepeater.dylib, 6): no suitable image found.  Did find:
    /mydir/librepeater.dylib: mach-o, but wrong architecture

Do I have to do something different to load a dynamic library in Python on Mac OS X?

+1  A: 

Nope. As the error message says, there's an architecture mismatch between your python and librepeater.dylib file. Use file to check what the architecture of librepeater.dylib is; your python is going to be built using one of the ones not listed.

Aaron Gallagher
Using `file` did the trick: I modified the architecture in the compiler settings to match the python installation and now it works. Thanks!
nolk
Were you using the Apple-supplied Python? If so, you could have just run in 32-bit mode as suggested. But recompiling works, too. This is also why binaries on OS X are usually built as multi-architecture files (for example, i386, x86_64, and ppc) so the resultant files, libs, or apps can be used on the various kinds of machines supported by the OS level.
Ned Deily
+2  A: 

It's not just a question of what architectures are available in the dylib; it's also a matter of which architecture the Python interpreter is running in. If you are using the Apple-supplied Python 2.6.1 in OS X 10.6, by default it runs in 64-bit mode if possible. Since you say your library was compiled as 32-bit, you'll need to force Python to run in 32-bit mode. For the Apple-supplied Python, one way to do that is to set a special environment variable:

$ python -c "import sys; print sys.maxint"
9223372036854775807
$ export VERSIONER_PYTHON_PREFER_32_BIT=yes
$ python -c "import sys; print sys.maxint"
2147483647

See Apple's man 1 python for more information.

Ned Deily
+1, right on target.
Alex Martelli