tags:

views:

380

answers:

4

Hello everyone!

I wrote a library and want to test it. I wrote the following program, but I get an error message from eclipse.

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char **argv) {
    void *handle;
    double (*desk)(char*);
    char *error;

    handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    desk= dlsym(handle, "Apply"); // ERROR: cannot convert from 'void *' to 'double*(*)(char*)' for argument 1
    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    dlclose(handle);
}

What is wrong?

Regards.

+2  A: 

You need to explicitly cast the return value of dlsym(), it returns a void* and desk is not of type void*. Like this:

desk = (double (*)(char*))dlsym(handle, "some_function");

kbyrd
Huh, I didn't think about it. I explicitly cast as much as I can, I don't like the hidden fun of implicit casts. I'll remove the ding about C vs. c++.
kbyrd
This might compile in a C compiler though, right? A C++ compiler will require the cast. Or am I wrong?
Andrew Flanagan
(sorry -- deleted comment and then re-added -- confusing)
Andrew Flanagan
In this case it's generally nice to have a typedef for your function pointer so you can cast it without your code line looking like a mess of parens and asterisks.
Josh K
Now I get this exeption:undefined reference to 'dlerror' ...'dlsqm' ... 'dlclose'Do you know a solution?
Are you linking in dl? Try adding '-ldl' the the compiler cmdline.
kbyrd
A: 

Does an explicit cast work...?

Andrew Flanagan
A: 

Basically you need to apply a cast to the return value of dlsym when assigning it to desk. In this article, they cast the void* return to their function pointer.

Look at this article.

Doug T.
+3  A: 

In C++ you need the following:


typedef double (*func)(char*);
func desk = reinterpret_cast<func>( dlsym(handle, "Apply"));
Nikolai N Fetissov
Your syntax for reinterpret_cast is wrong.
Brian Neal
Yep, html ate my angle brackets :) Fixed, thatnks.
Nikolai N Fetissov
Now I get this exeption: undefined reference to 'dlerror' ...'dlsqm' ... 'dlclose' Do you know a solution? Spasibo!
I said this below, but I'll add it here too: Are you linking in dl? Try adding '-ldl' the the compiler cmdline.
kbyrd
@kbyrd is right - try -ldl
Nikolai N Fetissov