2

次のコードを含む dylib を作成しました。

    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

dylib をコンパイルして別のプロジェクトに配置しましたが、dylib から Test オブジェクトを作成していくつかのメソッドを呼び出す方法がわかりません。
誰でもこれを行う方法を知っていますか?
ありがとう、
マット

4

1 に答える 1

2

参考までに、動的ライブラリは実行時にロードされます。コードを動的にロードする必要がない場合は、静的にリンクします。

ともかく:

#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];
}

いくつかのエラー チェックを含めたいと思うでしょうが、それが基本的な考え方です。NSBundle を使用する場合 (状況によっては、より「適切な」場合があります。http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.htmlを参照してください)

于 2011-02-26T21:30:52.717 に答える