Question

Hi Im loading functions dynamically and executing them. I want be able to define a generic return type so that compiler can clean up the stack properly. Currently its printing gibberish for version string.

How can I make the following code work?

// gcc -o test test.c -ldl

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

typedef union  { int i; double d; float f; char *p;} anytype; 

int main()
{
  anytype ver2;

  anytype (*f)();

    void *handle = dlopen("libz.so.1", RTLD_NOW|RTLD_GLOBAL);
    f = dlsym(handle,"zlibVersion");
    //const char * zlibVersion (void);
    ver2=f();
    printf("zlib version %s\n", ver2.p);
    dlclose(handle);

    return 0;
}
Was it helpful?

Solution

Unfortunately, you cannot use a union to substitute for a return value of an unknown type. On architectures which have floating point registers, a floating point return value is returned in a floating point register, while an integer or pointer return value is returned in a general purpose register. Usually, if the return value is a union or struct, the caller must provide a first argument pointing to a storage area (of the correct size) which the callee will fill in with the return value. (There are lots of variations. It's completely dependent on the platform ABI; what I described is (part of) the i386 ABI.)

So you really need to know the signature of the function in order to call it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top