检索当前/自己的包的路径
问题描述:
在编写跨平台模块时,我需要一种方法来检索模块目录的路径(以便可以访问模块文件夹中的文件,例如配置和资源)。我的模块,当前编译为一个包,由任意进程加载。获取我的模块的路径很容易在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;
}
答
[[NSBundle bundleForClass:[thisClass class]]bundlePath];
将动态库工作...
或者如果你正在寻找你的主
[[NSBundle mainBundle] bundlePath];
也bundleURL ......看到NSBundle Documentation
那么你的资源应该是相对于你的主束。 您可以使用
[[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponents:@[@"Contents",@"Resources"]];
非常感谢。我对所有与objective-c相关的东西都是全新的(否则使用C++),你可以在第一个例子中扩展一下(我很确定这就是我想要的!)? 具体来说,thisClass引用什么 - 由返回的包实例化的类?我看到有些人这样做,这是否有效? NSBundle * bundle = [NSBundle bundleForClass:[self class]]; 之后,我会在返回的bundle上调用bundlePath来检索它的路径? – Shaggi
@Shaggi类既是类又是实例方法,所以任何本地类或实例...例如'[MyDog类]或'[aDog类]'应该返回相同的东西... –
我得到了它的工作 - 谢谢你这么多 - 用实例来更新主题。 – Shaggi