Reputation: 47
Hi i am trying to implement shared library (dynamic linking) below is the code i am getting error as below please help me to fix it
error: invalid conversion from ‘void*’ to ‘double (*)(int*)’ [-fpermissive]
fn = dlsym(lib_handle, "ctest1");
ctest1.c
void ctest1(int *i)
{
*i=5;
}
Above ctest1.c is the shared library which is used in the below hello.cc file
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "ctest1.h" // here i have declared the function of shared library
int main(int argc, char **argv)
{
void *lib_handle;
void (*fn)(int *);
int x=990;
char *error;
lib_handle = dlopen("libp.so", RTLD_LAZY); // opening the shared library
if (!lib_handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
fn = dlsym(lib_handle, "ctest1"); //storing the address of shared library function
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(1);
}
fn(&x);
printf("getting x value from shared library=%d\n",x);
dlclose(lib_handle);
return 0;
}
~
~
~
Upvotes: 0
Views: 1133
Reputation: 53016
You are simply invoking the wrong compiler. In c++ you can't convert from void *
to another pointer type without casting. If this is not your code then, the lack of a cast means that the code is c instead of c++. Please read the tags wiki to understand, c and c++ are not the same language, they are somewhat similar but, certainly not the same.
This is from draft n1570 of the c standard
6.3.2.3 Pointers
- A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
If it's your code you should distinguish between c and c++ by using the appropriate file extension, or force the compiler to use the appropriate compiler which I don't recommend, just fix the file extension.
Upvotes: 3
Reputation: 31173
dlsym
returns a void*
and you are trying to store that in the function pointer. You have to use a cast for it to succeed when using c++ (assuming from tags and file ending .cc, though your code is actually C).
Also your type claims the function has a return type of double
but your library function returns void
. This will have to be fixed or you will get runtime problems.
Upvotes: 1