Skip to content

Instantly share code, notes, and snippets.

@rweichler
Last active January 1, 2016 17:49
Show Gist options
  • Save rweichler/8179299 to your computer and use it in GitHub Desktop.
Save rweichler/8179299 to your computer and use it in GitHub Desktop.
Dynamically load a library at runtime WOOOOOOooOOO
#include <Foundation/Foundation.h>
@interface Base : NSObject
@property (nonatomic, readonly) NSString *name;
@end
#include "base.h"
@implementation Base
-(NSString *)name
{
return @"this is the baseclasses name";
}
@end
#include <dlfcn.h>
#include <stdio.h>
#include "base.h"
int main(int argc, char **argv)
{
void *lib = dlopen("dylib.dylib", RTLD_NOW);
if(lib == NULL)
{
printf("ERROR!!!\n");
return 1;
}
Base *sub = [[NSClassFromString(@"Sub") alloc] init];
printf("%s\n", sub.name.UTF8String);
dlclose(lib);
return 0;
}
CC=clang
FLAGS=-framework Foundation -ObjC
all: output.txt
clean:
rm exec dylib.dylib output.txt
output.txt: exec dylib.dylib
./exec > output.txt
cat output.txt
exec: main.m base.m
$(CC) $^ $(FLAGS) -o $@
dylib.dylib: sub.m
$(CC) $^ $(FLAGS) -dynamiclib -undefined suppress -flat_namespace -o $@
this is the subclass that was dynamically loaded at runtime :D
#include "base.h"
@interface Sub : Base
@end
#include "sub.h"
@implementation Sub
-(NSString *)name
{
return @"this is the subclass that was dynamically loaded at runtime :D";
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment