2011-02-26 72 views
1

我做了一個包含下面的代碼dylib:如何在Obj-C應用程序中訪問和使用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並調用一些方法。
任何人都知道如何做到這一點?
謝謝,
馬特

回答

1

只是:動態庫在運行時加載。如果您不需要動態加載代碼,請靜態鏈接。

總之:

#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

+0

您的代碼似乎無法正常工作。我會發布我的代碼,但我無法弄清楚如何做代碼標籤。 – Matt 2011-02-26 21:43:19

+0

請定義「不出現工作」。 – 2011-02-27 02:05:31

+0

我設置了它,因此我創建了一個全局的Test對象,即使我將其稱爲它,也不會發生嗶聲。 – Matt 2011-02-27 02:16:41

相關問題