1,创建一个dylib的工程, 工程名为 TestDylib
2,创建一个接口文件 MyProtocol.h
#import <Foundation/Foundation.h> @protocol MyProtocol <NSObject> -(void)sayHello; @end
#ifndef TestDylib_MyObjectInstance_h #define TestDylib_MyObjectInstance_h #import <Foundation/Foundation.h> #import "MyProtocol.h" #import "TestDylib.h" extern id<MyProtocol> get_MyObjectInstance(void); #endif
get_MyObjectInstance函数
#import <Foundation/Foundation.h> #import "MyProtocol.h" #import "MyObjectInstance.h" @interface TestDylib : NSObject<MyProtocol>{ } @end
#import "TestDylib.h" @implementation TestDylib - (id)init{ self = [super init]; if (self) { } return self; } -(void)sayHello{ NSLog(@"Hello World"); } @end extern id<MyProtocol> get_MyObjectInstance(void){ TestDylib *test = [[TestDylib alloc] init]; return [test autorelease]; }
6, 创建一个Application工程 Example, 在AppDelegate.m中调用dylib
#import "AppDelegate.h" #import "MyObject.h" #include <stdio.h> #include <dlfcn.h> #import <Foundation/Foundation.h> #import <objc/runtime.h> #import "MyProtocol.h" @implementation AppDelegate @synthesize window = _window; - (void)dealloc{ [super dealloc]; } - (void)applicationDidFinishLaunching:(NSNotification *)aNotification{ NSString *dyPath = @"/Users/Leon/Desktop/TestDylib.dylib"; void *handle = dlopen([dyPath cStringUsingEncoding:NSUTF8StringEncoding], RTLD_LAZY); if (handle) { NSLog(@"open dylib success"); id<MyProtocol>(*function)() = dlsym(handle, "get_MyObjectInstance"); if (function) { NSLog(@"open function success"); id<MyProtocol> testDylib = (id<MyProtocol>)function(); if (testDylib) { [testDylib sayHello]; } } dlclose(handle); } } @end