Search code examples
pythonccython

Can Cython .so files be used in C?


I used Cython recently and discovered that it outputs a .so file. Can I use the .so file in my C program and if so, how do I implement that?


Solution

  • Yes, assuming that the SO file exports its internal functions to the dynamic linking scope, where a linker/library can find its functions (See dlfcn.h). From there, you can call the functions that you have in the SO file.

    A very simple C code would look like this:

    #include <dlfcn.h>
    #include <assert.h>
    
    int main(int argc, char** argv) {
        void* dlhandle = dlopen("path/to/your/library", RTLD_LAZY);
        assert(dlhandle != NULL);
    
        void (*function_name)(int func_params) = dlsym(dlhandle, "func_name");
        // Check for NULL again
    
        // Call your function etc
        return 0
    }
    

    Technically, you can also dynamically link to it as a system library too. I wouldn't recommend it though for a variety of reasons.