【问题标题】:How can I find the path to a file in an application bundle (NSBundle) using C?如何使用 C 在应用程序包 (NSBundle) 中找到文件的路径?
【发布时间】:2021-04-18 03:31:15
【问题描述】:

是否有用于在应用程序包中查找文件路径的 C API?

我知道这可以在 Objective-C 中使用以下语法来完成。

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyImage" ofType:@"bmp"];

我是否也可以从 C 或 C++ 代码中调用相应的函数?

【问题讨论】:

    标签: c macos core-foundation nsbundle


    【解决方案1】:

    Mike K pointed me in the right direction 之后,我能够使用以下代码检索应用程序包中文件的路径。

    // Get a reference to the main bundle
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    
    // Get a reference to the file's URL
    CFURLRef imageURL = CFBundleCopyResourceURL(mainBundle, CFSTR("MyImage"), CFSTR("bmp"), NULL);
    
    // Convert the URL reference into a string reference
    CFStringRef imagePath = CFURLCopyFileSystemPath(imageURL, kCFURLPOSIXPathStyle);
    
    // Get the system encoding method
    CFStringEncoding encodingMethod = CFStringGetSystemEncoding();
    
    // Convert the string reference into a C string
    const char *path = CFStringGetCStringPtr(imagePath, encodingMethod);
    
    fprintf(stderr, "File is located at %s\n", path);
    

    这似乎比它需要的要长一点,但至少它有效!

    【讨论】:

      【解决方案2】:

      您可以通过以下方式获取主包:

      CFBundleRef mainBundle = CFBundleGetMainBundle();
      

      这里有完整的细节:

      http://developer.apple.com/library/mac/#documentation/CoreFOundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-27
        • 2019-08-22
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多