PDA

View Full Version : dlopen for loading plugins


unknown
2006.04.18, 01:17 PM
Trying to get dlopen to work..

From tutorials on the net and so on, ive written this code:

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

#include <dlfcn.h>

int main(int argc, char *argv)
{
char *error;

void *my_plugin = dlopen("test.o", RTLD_LAZY);
if (!my_plugin) {
fprintf (stderr, "%s\n", dlerror());
exit(1);
}

void (*func)(void) = dlsym(my_plugin, "external_function");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s\n", error);
exit(1);
}

func();

dlclose(my_plugin);

return 0;
}


and the plugin I want to test with is like this:


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

void external_function()
{
printf("Success!\n");
}



But I can't get it to work, I dont know how to compile my plugin correctly. A lot of advice on the internet is to use -shared, but that isn't recognized.

Anyone know what I need to do here?
Thanks.

ThemsAllTook
2006.04.18, 01:48 PM
Nifty, I didn't know about dlopen. I'll have to remember this.

I got it to work by compiling the plugin code with -dynamiclib.

unknown
2006.04.18, 02:29 PM
Thanks a lot ThemsAllTook. Awesome!

TomorrowPlusX
2006.04.18, 03:17 PM
I don't know if dlopen was added to 10.4 or not, it certainly didn't exist in 10.3. I've been using the dlcompat library to do this, until I recently had to do some stuff which dlopen didn't support -- namely aliasing exported functions in the running executable itself ( for C++ classloading trickery ).

I found the function CFBundleGetFunctionPointerForName works *really* well.