How To Access User Defined Data Types Declared In .so (shared Libraries) In C

- 1 answer

I have some external .so file. I am writing a program to call some of the API's of the .so library.

I have used dlopen and dlsym as below

void *handle = dlopen ("/new_project/lib/", RTLD_LAZY);
void (*fptr)(char *);
fptr = dlsym((void *) handle, "func1");

I was able to call func1(char *)

However I am not sure how to call the api which requires a object of the structure that is defined in the .so file. For example

func2(structure1 obj1);

Even tried to use dlopen using RTLD_NOW | RTLD_GLOBAL. Nothing worked.

Any help here is appreciated.



C does not have runtime-dynamic types. Assuming you know what library you will be loading at the time you write/build your program, or even just know what types it uses in its public interfaces, you include the appropriate headers to declare those types.

If you don't know that, but the data of dynamic type is only passed by reference (e.g. with void * pointers), then if the library provides some sort of description of the type to you at runtime (e.g. a table of member, their types, and their offsets) then you can malloc storage for such an object and build it dynamically using that information and pass it to the library.

If the library needs dynamic types passed by value, then you are dealing with a foreign function interface outside the scope of what you can do in C with dlopen alone, and you need a FFI implmentation supporting the C implementations you care about, such as libffi, which can construct and make calls dynamically.