检索当前/自己的bundle的路径

Retrieving path to current/own bundle

本文关键字:bundle 路径 自己的 检索      更新时间:2023-10-16

在编写跨平台模块时,我需要一种方法来检索模块目录的路径(因此我可以访问模块文件夹中的文件,如配置和资源)。我的模块,目前被编译为一个bundle,可以被任意进程加载。获取模块的路径在windows中很容易完成,如下所示:

GetModuleFileName(GetModuleHandle(0), buf, size); // copies the path of the current DLL into buf

我还没能在OSX上找到类似的方法。我尝试了_NSGetExecutablePath(),但它只检索主程序的路径。

但是,它也获得主可执行文件的路径。在OSx上这样做的常用方法是什么?

编辑:

grady player向我展示了方法:)我使用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;
}
[[NSBundle bundleForClass:[thisClass class]]bundlePath];

将用于动态库…

或者如果你正在寻找你的主

    [[NSBundle mainBundle] bundlePath];

也bundleURL…参见NSBundle Documentation

那么你的资源应该是相对于你的主包的。你可以使用

 [[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponents:@[@"Contents",@"Resources"]];