我有一个 iOS 项目,我在其中使用了一些 C 源代码。 在 C 部分,我需要主包中文件的路径。 如何在不使用 Obj-C 的情况下获取它?
基本上我希望通过以下方式返回路径:
NSLog(@"%s",[[[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"] fileSystemRepresentation]);
最佳答案
所以只要像上面那样获取路径,然后得到一个C字符串版本:
NSString *path = [[[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"] fileSystemRepresentation];
char *cPath = [path cStringUsingEncoding:UTF8StringEncoding];
只要注意文档中的警告并复制字符串,如果你打算在你所在的方法/函数结束后继续使用它:
The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current autorelease pool is emptied, whichever occurs first. You should copy the C string or use getCString:maxLength:encoding: if it needs to store the C string beyond this time.
更新:如果出于某种原因您不能使用 Foundation,您可以使用 Core Foundation 做类似的事情。您可以调用 CFBundleCopyResourceURL()
(或其表亲之一)来获取资源的 URL,然后使用 CFURLCopyPath()
将其转换为路径。
关于objective-c - iOS:在c代码中获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13648763/