我的主程序将加载一个名为hello.so的简单动态库
主要的
void* handle = dlopen("./hello.so", RTLD_LAZY);在main中 ,传递一个名为testing的回调函数(在main.h中的某个地方定义)并从动态库中调用hello()
typedef void (*callback)(); typedef void (*hello_t)( callback); /* do something */ hello_t hello = (hello_t) dlsym(handle, "hello"); hello(testing);在动态库中,
#include #include "main.h" extern "C" void hello( void (*fn)() ) { /*do something and then invoke callback function from main */ fn(); }除了使用回调之外,还有其他方法允许从动态库调用/使用main的函数/数据吗?
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?
最满意答案
不,在我看来,这是做这件事的首选方式。 我能想到的任何其他方式都涉及让DLL知道它所链接的程序中的对象,这很可能是不好的做法。
关于数据,只是提醒您虽然没有提出要求,但通常最好的做法是复制需要存储的任何数据,如果它通过库/程序边界传递的话。 如果您使用的数据库的生命周期由程序控制,则可能会陷入完全混乱,反之亦然。
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.
更多推荐
发布评论