Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a shared library from c++

Tags:

c++

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.

like image 531
chavalisurya Avatar asked Apr 26 '16 17:04

chavalisurya


People also ask

How do you call a function in a shared library?

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.

What is shared library in C?

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.

How do I open a shared library file?

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).


1 Answers

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.

like image 178
user2622016 Avatar answered Nov 07 '22 05:11

user2622016