How to access and use a dylib in an Obj-C application?

本秂侑毒 提交于 2019-12-24 00:51:48

问题


I've made a dylib that contains the following code:

    Test.h:

#import <Cocoa/Cocoa.h>
@interface Test : NSObject {
     int number;
}
-(void)beep;
-(void)giveInt:(int)num;
-(int)takeInt;

@end


Test.m:

#import "Test.h"

@implementation Test

-(void)beep {
     NSBeep();
}
-(void)giveInt:(int)num {
     number = num;
}
-(int)takeInt {
     return number;
}

@end

I've compiled the dylib and put it in another project but I can't seem to figure out how to make a Test object from the dylib and call some of the methods.
Anyone know how to do this?
Thanks,
Matt


回答1:


Just fyi: Dynamic libraries are loaded at runtime. If you don't need to load code dynamically, link statically.

Anyway:

#import "test.h"
#include <dlfcn.h>

int main(int argc, const char *argv) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    void *handle = dlopen("test.dylib", RTLD_LAZY);
    id t = [[NSClassFromString(@"Test") alloc] init];

    [t beep];
    [t release];

    dlclose(handle);
    [pool drain];
}

You'll want to include some error checking, but that's the basic idea. If you want to use NSBundle (which may be more "proper" depending on the circumstances, see http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html)



来源:https://stackoverflow.com/questions/5129022/how-to-access-and-use-a-dylib-in-an-obj-c-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!