Gazolike
Gazolike

Reputation: 51

Cython dynamic library linking

I'm actually trying to link an existing C library to my Cython program.

I have access to the entrypoint header (.h) of the library with all functions declared as:

EXPORT_API int _stdcall LibFunction();

I suppose the EXPORT_API is used to create the dll with __declspec(dllexport)...

I also have access to the .lib and .dll files.

I've tried to use this function with the usual cdef extern fromof Cython:

cdef extern from "include\\entrypoint.h":
    int LibFunction()

def c_LibFunction():
    LibFunction()

And I'm using the following setup.py

from setuptools import setup, Extension
from Cython.Distutils import build_ext

NAME = 'testlib'
REQUIRES = ['cython']
SRC_DIR = 'testlib'
PACKAGES = [SRC_DIR]

INCLUDE_DIR = 'testlib\include'
LIB_DIR = 'testlib\lib'

ext = Extension(SRC_DIR + '.wrapped',
                [SRC_DIR + '/wrapped.pyx'],
                include_dirs=[INCLUDE_DIR],
                library_dirs = [LIB_DIR],
                libraries=['cfunc', 'MyLib']
                )

if __name__ == "__main__":
    setup(
            install_requires=REQUIRES,
            packages=PACKAGES,
            name=NAME,
            ext_modules=[ext],
            cmdclass={"build_ext": build_ext}
            )

But when I compile my Cython python setup.py build_ext I get an unresolved external reference:

error LNK2001: unresolved external symbol __imp_LibFunction

As I found on other thread it seems so be a question of static or dynamic library linking.

I think it comes from the setuptools compiling options, I tried to investigate using distutils documentation and Cython documentation.

The thing is, I also tried to do my own C library (cfunc.lib, a static one) and I managed to use function in it the same way I described above.

I also used DUMPBIN on MyLib.lib and I found the symbo int __cdecl LibFunction(void)and as expected, the __imp_ is not in the symbol.

It someone has an idea of what's going on, why it's going on and how I can solve my problem it could be really helpful !

Upvotes: 4

Views: 2569

Answers (1)

Gazolike
Gazolike

Reputation: 51

I finally found the solution so I post it if someone needs help in the future !

I work on Windows using Visual Studio to compile my code.

Even if I created my cfuncproject as a Visual C++ project, it didn't compile as a C++ project but as a C project so it worked by default (it only has a .c and a .h files).

My entrypoint.h only contains C-style function declaration but the dll is compiled as a C++ project, that's why it couldn't work, the name mangling was bad.

So I just added language = 'c++'in my setup.py

Upvotes: 1

Related Questions