Question

The CFBundleCopyExecutableURL function some times return an absolute URL and some times no. if call CFBundleCopyExecutableArchitectures before the CFBundleCopyExecutableURL, the url is absolute (Why?). How to enforce this function to always return absolute URL? thanks.

text getBundleExeutableUrl(text bundlePath)
{
    CFURLRef url = CFURLCreateFromFileSystemRepresentation(0,
        (char*)bundlePath.c_str(), bundlePath.length(), false);
    CFBundleRef bundle = CFBundleCreate(0, url);
    CFBundleCopyExecutableArchitectures(bundle); // this is necessary to get absolute path
    CFURLRef exeUrl = CFBundleCopyExecutableURL(bundle);
    CFStringRef srExe = CFURLCopyFileSystemPath(exeUrl, 0);
    text bundleExe = srExe;
    CFRelease(srExe);
    CFRelease(exeUrl);
    CFRelease(url);
    CFRelease(bundle);
    return bundleExe;
}
Was it helpful?

Solution

In your source code, add this extra line which refers to CFURLCopyAbsoluteURL

CFURLRef exeUrl = CFBundleCopyExecutableURL(bundle);
CFURLRef absoluteURL = CFURLCopyAbsoluteURL(exeURL);
CFStringRef srExe = CFURLCopyFileSystemPath(absoluteURL, 0);
CFRelease(absoluteURL); // don't forget to release what you create

"CFURLCopyAbsoluteURL" will convert a relative URL to an absolute URL.

You should probably also have some error checking lines in your code (e.g. make sure URL's are not NULL before proceeding, etc.).

Also, one style thing I wanted to mention is that object and variable declarations (e.g. your "text") are usually capitalized (e.g. "CFStringRef", "NSString", etc.). Parameters and variable names are what start off as lower case. Also, "text" is confusing. Just call it the "CFStringRef" that it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top