MAC开发动态调用dylib

1,创建一个dylib的工程, 工程名为 TestDylib

2,创建一个接口文件 MyProtocol.h

#import <Foundation/Foundation.h>

@protocol MyProtocol <NSObject>
-(void)sayHello;
@end

3,创建一个.h的文件 MyObjectInstance.h, 这个方法是用来初始化对象的时候调用,这样就可以不用include对象的头文件。

#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

4, 创建一个NSObject, TestDylib.h TestDylib.m, 在TestDylib.m中实现
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];
}

5, build project, 将dylib文件拷贝到桌面

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




你可能感兴趣的:(function,application,Build,include,interface)