1
在編寫跨平臺模塊時,我需要一種方法來檢索模塊目錄的路徑(以便可以訪問模塊文件夾中的文件,例如配置和資源)。我的模塊,當前編譯爲一個包,由任意進程加載。獲取我的模塊的路徑很容易在Windows中完成,如下所示:檢索當前/自己的包的路徑
GetModuleFileName(GetModuleHandle(0), buf, size); // copies the path of the current DLL into buf
我一直沒能在OSX上找到類似的方法。我試過_NSGetExecutablePath()
,但它只檢索主程序的路徑。也試過the method here。
但是,它也獲得了主要可執行文件的路徑。在OSx上這樣做的常用方法是什麼?
問候
編輯:
格雷迪播放器顯示我的方式:)我編譯使用一個NSBundle下面的代碼:
/*
this could be anything apparantly
*/
@interface dummyObject : NSObject
- (void) dummyMethod;
@end
@implementation dummyObject
- (void) dummyMethod {
}
@end
int GetBundlePath(char * buf, int bufSize)
{
NSString * path = [[NSBundle bundleForClass:[dummyObject class]]bundlePath];
const char * intString = [path UTF8String];
int length = strlen(intString);
int smallestLength = length > bufSize ? bufSize : length;
memcpy(buf, intString, smallestLength);
[path release];
return smallestLength;
}
非常感謝。我對所有與objective-c相關的東西都是全新的(否則使用C++),你可以在第一個例子中擴展一下(我很確定這就是我想要的!)? 具體來說,thisClass引用什麼 - 由返回的包實例化的類?我看到有些人這樣做,這是否有效? NSBundle * bundle = [NSBundle bundleForClass:[self class]]; 之後,我會在返回的bundle上調用bundlePath來檢索它的路徑? – Shaggi
@Shaggi類既是類又是實例方法,所以任何本地類或實例...例如'[MyDog類]或'[aDog類]'應該返回相同的東西... –
我得到了它的工作 - 謝謝你這麼多 - 用實例來更新主題。 – Shaggi