Reputation: 207
I have come across something similar to this piece of code today.
In A.h
:
class A { blah blah blah }
#define CREATE_A_FUNC_NAME ("CreateA")
extern "C" A* CreateA(void);
typedef A* (*funcCreateA)(void);
In main.cpp
:
void* handle = dlopen("libA.so", RTLD_LAZY);
funcCreateA func = (funcCreateA)dlsym(handle, CREATE_A_FUNC_NAME);
A* a = func();
Now obviously A.h is only the header for declarations and all its implementations are stored in libA.so
.
I have tested that if I set up my project correctly, meaning the lib is correctly linked, I can simply do A* a = CreateA()
to get the pointer to a newly created A instance. Hence here come the questions. Why go through so much hassle to achieve something simple as one function call? What is this kind of technology or technique called? What are the pros and cons? When should I use this technique? Thanks!
Upvotes: 0
Views: 2764
Reputation: 9672
The main reasons to use dlsym rather than linking to the DSO directly:
It's worth noting that if you link to the DSO directly, under the hood, the linker will simply insert dlsym/dlopen code at app start up, which will automatically load the DSO and resolve the symbols.
Upvotes: 4