简体   繁体   中英

I get an error, when using C-library with Cython

In Qt Creator I created a small library (in 'Squaring' subfolder of Python project):

squaring.h:

int squaring(int a);

squaring.c:

#include "squaring.h"
int squaring(int a){
    return a * a;
}

In Eclipse, I created Python project that tries to use this library ( according to the instructions from the official website) :

cSquaring.pxd:

cdef extern from "Squaring/squaring.h":
    int squaring(int a)

Functions.pix:

cimport cSquaring
cpdef int count(int value):
    return cSquaring.squaring(value)

setup.py:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(ext_modules=cythonize([Extension("Functions", ["Functions.pyx"])]))

main.py:

from Functions import count
if __name__ == '__main__':
    data = 1
    returned = count(data)
    print(returned)

Completed the compilation of C code using (without any errors):

python3 setup.py build_ext -i

But when I run main.py on execution, I get ImportError:

File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 2643, in <module>
main()
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 2636, in main
globals = debugger.run(setup, None, None, is_module)
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 1920, in run
return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 1927, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/_pydev_imps/_pydev_execfile.py”, line 25, in execfile
exec(compile(contents+“\n”, file, ‘exec’), glob, loc)
File “/home/denis/eclipse-workspace/ConnectionWithCPlusPlus/main.py”, line 1, in <module>
from Functions import count
ImportError: /home/denis/eclipse-workspace/ConnectionWithCPlusPlus/Functions.cpython-37m-x86_64-linux-gnu.so: undefined symbol: squaring

And another project where the code is used Cython (there I did not create A C-library, and wrote the code directly on Cython) works fine.

What is the problem?

You included the header files in Cython, but you never actually told it about the implementation , ie the library where the function is defined. You need to link against the library generated by compiling your C source, as described in the Cython docs .

In your Functions.pyx , you have to add a comment like this to the top.

# distutils: sources = path/to/squaring.c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM