i have a shared library with some functions stored inside it. i want to Access those functions by calling that library from another program. I have done this earlier in C.
Now i want to do the same using C++. I am pretty new to C++ and any suggestions are very much required. BTW, the shared library is written in C. Is it still possible for me to call this in a C++ program and use all the functions of it. Please help me. An example program would be very very helpful.
i am using ubuntu 14.04 and the compiler is the native g++ that comes along with it.
Dynamically calling a function from a shared library can only be accomplished in Go using 'cgo' and, even then, the function pointer returned by 'dlsym' can only be called via a C bridging function as calling C function pointers directly from Go is not currently supported. Output: Same as C entry.
Shared libraries (also called dynamic libraries) are linked into the program in two stages. First, during compile time, the linker verifies that all the symbols (again, functions, variables and the like) required by the program, are either linked into the program, or in one of its shared libraries.
If you want to open a shared-library file, you would open it like any other binary file -- with a hex-editor (also called a binary-editor). There are several hex-editors in the standard repositories such as GHex (https://packages.ubuntu.com/xenial/ghex) or Bless (https://packages.ubuntu.com/xenial/bless).
Load shared libarary using dlopen, and load given symbol using dlsym. Link with -ldl
.
So given a shared library hello.cpp, compile g++ -shared -fPIC -o libhello.so hello.cpp
#include <cstdio>
extern "C" void hello( const char* text ) {
printf("Hello, %s\n", text);
}
(shared libraries should be named lib*.so[.*]
)
Now calling in main.cpp, compile: g++ -o main main.cpp -ldl
#include <dlfcn.h>
extern "C" typedef void (*hello_t)( const char* text );
int main() {
void* lib = dlopen("./libhello.so", RTLD_LAZY);
hello_t hello = (hello_t)dlsym( lib, "hello" );
hello("World!");
dlclose(lib);
}
See C++ dlopen mini HOWTO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With