Cython: library reference and call function
I'm trying to write a Cython wrapper for the C library. I've read the docs carefully, but I must be missing something because I can't get the following simple Cython code to work.
I created a shared library from the following:
mathlib.c
#include "mathlib.h"
int add_one(int x){
return x + 1;
}
mathlib.h
extern int add_one(int x);
Then I created a library like this:
gcc -c mathlib.c gcc -shared -o libmathlib.so mathlib.o -lm
My Cython files are mathlib.pyx, cmathlib.pyd and setup.py
cymathlib.pyx
from mathlib cimport add_one
def add_one_c(int x):
print add_one(x)
return x
mathlib.pyd
cdef extern from "mathlib.h":
int add_one(int x)
setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
ext_modules = cythonize([Extension("cymathlib", ["cymathlib.pyx"])], libraries ["mathlib"]`enter code here`)
)
The module cymathlib.so is created, but when I try to import it into Python I get the following error: ImportError: dlopen (./cymathlib.so, 2): Symbol not found: _add_one Link to. / cymathlib. so what is expected in: flat namespace in. /cymathlib.so "
source to share
It looks like something went wrong with your spec Extension
, which should be something like this:
ext_modules = cythonize([Extension("cymathlib",
["cymathlib.pyx"],
libraries=["mathlib"],
library_dirs=["/place/path/to/libmathlib.so/here"]
)])
To be able to use a module, it must be able to find libmathlib.so
at runtime, as it will look in that file for the actual implementation add_one
. Besides copying the file to / usr / lib or / usr / local / lib (and rerunning ldconfig), you can also set an environment variable to make sure the library can be found:
export LD_LIBRARY_PATH=/place/full/path/to/libmathlib.so/here
It is also possible to add C code to the python module you are creating (so libmathlib.so no longer needs to be compiled or used). You just need to add the file mathlib.c
to your cython sources list:
ext_modules = cythonize([Extension("cymathlib",
["cymathlib.pyx","mathlib.c"]
)])
source to share