Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data with a dynamically loaded library (dlopen,dlsym)

Tags:

c++

My main program would load a simple dynamic library called hello.so

In main


void* handle = dlopen("./hello.so", RTLD_LAZY);

In main , pass a callback function called testing (defined somewhere in main.h) and invoke the hello() from the dynamic library


typedef void (*callback)();
typedef void (*hello_t)( callback);

/* do something */

hello_t hello = (hello_t) dlsym(handle, "hello");
hello(testing);

In dynamic library,


#include 
#include "main.h"

extern "C" void hello( void (*fn)() ) {
  /*do something and then invoke callback function from main */  fn();
}


Are there other ways to allow functions/data of main to be called/used from dynamic library apart from using callbacks?

like image 388
user1492900 Avatar asked Feb 25 '26 22:02

user1492900


1 Answers

No, this is the preferred way of doing it, in my opinion. Any other way that I can think of involves making the DLL aware of the objects in the program it's linked with, which is most likely bad practice.

Regarding data, just a reminder though you didn't ask, it's usually best practice to copy any data that needs to be stored, if it's passed across library/program boundaries. You can get into a complete mess if you have the library using data whose lifetime is controlled by the program, and vice versa.

like image 172
Collin Dauphinee Avatar answered Feb 27 '26 11:02

Collin Dauphinee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!