Skip to content

Instantly share code, notes, and snippets.

@marcetcheverry
Created May 28, 2011 21:42
Show Gist options
  • Save marcetcheverry/55f57a1227acdec76c73 to your computer and use it in GitHub Desktop.
Save marcetcheverry/55f57a1227acdec76c73 to your computer and use it in GitHub Desktop.
Mac dylib at runtime
// Compile: clang -dynamiclib -Wl,-current_version 1.0 mylib.c -o mylib.dylib
// See it with otool -L mylib.dylib
//mylib.dylib:
// mylib.dylib (compatibility version 0.0.0, current version 1.0.0)
#include <stdio.h>
__attribute__((constructor))
static void initialize() {
printf("Initializing MyLib\n");
}
__attribute__((destructor))
static void destroy() {
printf("Destroying MyLib\n");
}
int printHello()
{
printf("Hello from MyLib\n");
return 22;
}
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
void *library = dlopen("mylib.dylib", RTLD_LAZY);
if (library == NULL)
{
const char *error = dlerror();
fprintf(stderr, "Could not open library\n");
if (error)
{
fprintf(stderr, "Could not open library: %s\n", error);
}
exit(EXIT_FAILURE);
} else {
void *initializer = dlsym(library, "printHello");
if (initializer == NULL)
{
fprintf(stderr, "Could not find printHello\n");
exit(EXIT_FAILURE);
}
else
{
// defines printHelloPtr as a pointer to a function taking void and returning int
typedef int (*printHelloPtr)(void);
printHelloPtr init_func = (printHelloPtr)initializer;
// with no typedef
/*
// Define a local variable
int (*init_func)(void);
// no need to cast, but if you do, the syntax requires no name in the type
init_func = (int(*)(void))initializer;
*/
int result = init_func();
printf("Got result %i\n", result);
}
}
if (dlclose(library) == -1)
{
const char *error = dlerror();
fprintf(stderr, "Could not close library\n");
if (error)
{
fprintf(stderr, "%s\n", error);
}
exit(EXIT_FAILURE);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment