Question

While writing a cross-platform module, I needed a way to retrieve the path to the module directory (so I can access files in the modules folder, like configs and resources). My module, currently compiled as a bundle, is loaded by arbitrary processes. Getting the path of my module is done pretty easily in windows, like so:

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

I haven't been able to find a similar method on OSX. I tried _NSGetExecutablePath() but it only retrieves the path of the main program. Also tried the method here.

However, it also gets the path of the main executable. What is the common method for doing so on OSx?

Regards

edit:

grady player showed me the way :) I compiled the following code using 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;
}
Was it helpful?

Solution

[[NSBundle bundleForClass:[thisClass class]]bundlePath];

will work for dynamic library...

or if you are looking for your main

    [[NSBundle mainBundle] bundlePath];

also bundleURL... see the NSBundle Documentation

then your resources should be relative to your main bundle. you can use

 [[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponents:@[@"Contents",@"Resources"]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top