Home > OS >  Can Cpython so files be used in C?
Can Cpython so files be used in C?

Time:07-25

I used CPython recently and discovered that it outputs a so file. The question is can I use the so file in my c program and if so how do I implement that?

CodePudding user response:

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.

  • Related