3

Possible Duplicate:
C++ Dynamic Shared Library on Linux

I am writing a shared object say libtest.so which has a class and a function. I have another program say "Program.cpp" from which i want to call the class and its function present in the libtest.so file. I am clueless as to how to proceed. Please help.

Thanks Regards Mahesh

Community
  • 1
  • 1
Mahesh
  • 31
  • 2

1 Answers1

1

Dynamically, you need to call dlsym to get the address of the function, and then call it through the pointer. The syntax for this is a bit tricky, since dlsym returns a void*, and there's no conversion between void* and a pointer to function. (Some compilers do allow it, although formally, in pre C++11, it required a diagnostic, as does the C standard.) The solution recommended in the Posix standard is:

int (*fptr)( int );
*(void**)(&fptr) = dlsym( handle, "function_name" );

This supposes that pointers to functions have the same size and format as pointers to data—not guaranteed by the C or C++ standards, but guaranteed by Posix.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • Hi James, Thank u for your response. Calling only a function from .so file is working. I want to call a function using the class object present in the .so file. – Mahesh Oct 05 '12 at 07:55
  • If it's a member function, just use `dlsym` to get the address of the object (a straight-forward cast from `void*` will do here), and call the function on it: `MyType* p = (MyType*)dlsym(...); p->function();` – James Kanze Oct 05 '12 at 08:09