Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
4.56/5 (2 votes)
See more:
I have a .so and header which has a class that all member of that are virtual
and I want to use the class and its functions in my main

I try following but it gives me segmentation fault

I haven't access to .so to change it

What I have tried:

CLASS_NAME * i;
void * h = dlopen("./LIBNAME.so",RTLD_NOW);
i = (CLASS_NAME *)dlsym(h, "CLASS_NAME");

i->Create(1);//member function
Posted
Updated 27-Aug-18 1:41am
v2
Comments
Richard MacCutchan 27-Aug-18 6:37am    
Since you have both header and shared object files, why not just use conventional compile and link?
saide_a 27-Aug-18 6:44am    
for compile I use this command in linux terminal:
g++ -o test test.cpp -ldl
is there something wrong?
Richard MacCutchan 27-Aug-18 7:31am    
You should also add the shared object library that you want to use, instead of trying to access it dynamically.
saide_a 27-Aug-18 7:39am    
many thanks for your response,
I used the command in this way also
g++ -o testcan testcan.cpp -L/lib path -lLIBNAME.so
but I got this error :/usr/bin/ld: cannot find -lLIBNAME.so
I added the library path in this way :
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/MyFirstProjects/
but I still get the same error
Richard MacCutchan 27-Aug-18 8:01am    
Try this (note the colon before LIBNAME.so):
g++ -o testcan testcan.cpp -L/lib path -l:LIBNAME.so

See ld(1): GNU linker - Linux man page[^] for full details of the various linker options.

1 solution

You will get a segmentation fault when i is NULL. Check if loading the library and getting the symbol was successful:
CLASS_NAME * i = NULL;
void * h = dlopen("./LIBNAME.so",RTLD_NOW);
// Get error message string upon errors
char *err = dlerror();
if (!h)
{
    // Report error here.
}
else
{
    i = (CLASS_NAME *)dlsym(h, "CLASS_NAME");
    if ((err = dlerror()) != NULL)
    {
        // Report error here.
    }
    else if (i)
    {
        i->Create(1);
    }
}
See also dlopen(3) - Linux man page[^].

Is there any specific reason that you are using dynamic loading? If not, just link your application with the library.
 
Share this answer
 
Comments
saide_a 27-Aug-18 6:48am    
I get segmentation fault error even if i is not Null
Jochen Arndt 27-Aug-18 7:59am    
Then it might be due to how the class is implemented in the library. The syntax from your example requires that dlsym() called with a class name returns a newly allocated instance of the object.

See also Dynamic Class Loading for C++ on Linux.
saide_a 27-Aug-18 8:12am    
No , it haven't function for returning instance :(
CPallini 27-Aug-18 7:20am    
5.
saide_a 27-Aug-18 7:50am    
could you help me for link my app to library?, in above I put my using command.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900