Python Tools and Dynamic Linking

I am writing several libraries in C that contain functions that I want to call from Python via ctypes.

I successfully executed this other library, but there were only very vanilla dependencies in this library (namely fstream , math , malloc , stdio , stdlib ). The other library I'm working on has more complex dependencies.

For example, I will try to use fftw3 . As a test, I will just try to compile a simple .cpp file containing:

 int foo() { void *p = fftw_malloc( sizeof(fftw_complex)*64 ); fftw_free(p); printf("foo called.\n"); return 0; } 

I will compile it as:

 icpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link icpc -shared -Wl,-soname,libwaveprop.so.1 -o libwaveprop.so.1.0 libwaveprop.o cp waveprop.so.1.0 /usr/local/lib/ rm waveprop.so.1.0 ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so.1 

It all works. Now I am testing it with another .cpp file containing:

 int main() { foo(); } 

Result:

 icpc test.cpp -lwaveprop /lib/../lib64/libwaveprop.so: undefined reference to `fftw_free' /lib/../lib64/libwaveprop.so: undefined reference to `fftw_malloc' 

This is quite reasonable. Then I try:

 icpc test.cpp -lwaveprop -lfftw3 ./a.out foo called. 

Excellent! But now when I try to load the library using ctypes:

 >>> from ctypes import * >>> print cdll.LoadLibrary('/usr/local/lib/libwaveprop.so.1') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib64/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: /usr/local/lib/libwaveprop.so.1: undefined symbol: fftw_free 

So the same problem, but I have no idea how to solve it for ctypes. I tried different things without any success, and I was pretty stuck at this point.

+4
source share
2 answers

OK, thanks for your help.

in order to get this to work, I had to include dependencies when binding (duh). I tried this before but got an error, so solve it, I had to recompile fftw with "-fpic" as the CPP flag. everything is working now.

 icpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link icpc -shared -Wl,-soname,libwaveprop.so.1 -o libwaveprop.so.1.0 libwaveprop.o -lfftw3 cp waveprop.so.1.0 /usr/local/lib/ rm waveprop.so.1.0 ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so.1 

thanks, -nick

+4
source

You need to link libwaveprop.so with the fftw3 library. Otherwise, Python simply won’t know where to go to get these missing characters; mind reading is not implemented in any programming language.

0
source

Source: https://habr.com/ru/post/1306459/


All Articles