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

2
  • 2
    Dynamically (with dlopen), or statically? In the latter case just add -ltest to your ld. Commented Oct 5, 2012 at 7:06
  • I am trying dynamically with dlopen. Commented Oct 5, 2012 at 7:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.