简体   繁体   English

将NSString转换为char *时找不到文件

[英]Cannot find file when converting NSString to char*

So I have a platform independent API that loads a file, it takes a char* as a value. 因此,我有一个独立于平台的API,用于加载文件,它以char *作为值。 I wrote some test code in the GetResource function that used a string literal and it worked fine. 我在GetResource函数中编写了一些使用字符串文字的测试代码,它工作正常。 However when I convert over to using the char* and converting back to an NSString the file can't be found. 但是,当我转换为使用char *并转换回NSString时,找不到该文件。

Working code: 工作代码:

bool GetResource(const char* filePath, uint8*& allocatedBuffer, uint32& size) {

    bool success = false;
    NSString* path = [[NSBundle mainBundle] pathForResource: "models/testModel" ofType: @"obj"];

Not Working code: 不起作用的代码:

NSString* nsModelString = @"models/testModel";
gDatastore->GetResource([nsModelString UTF8String], buffer, size);

....

bool GetResource(const char* filePath, uint8*& allocatedBuffer, uint32& size) {

    bool success = false;
    NSString* nsFilePath = [NSString stringWithFormat:@"%c" , filePath];
    NSString* path = [[NSBundle mainBundle] pathForResource: nsFilePath ofType: @"obj"];

Can anyone tell me what I am using wrong? 谁能告诉我我用错了什么? Is there an easy way to look at an NSString and see the contents? 有没有一种简单的方法可以查看NSString并查看其内容?

To look at the NSString to see the contents, you could either view it in the debugger or use: 要查看NSString来查看内容,可以在调试器中查看它,也可以使用:

NSLog(@"nsFilePath: %@", nsFilePath);

I think at least part of the problem is on this line: 我认为问题的至少一部分在这条线上:

NSString* nsFilePath = [NSString stringWithFormat:@"%c" , filePath];

%c is the format specifier for a single 8-bit unsigned char. %c是单个8位无符号字符的格式说明符。 For a C style string, you probably want to use %s , which is the format specifier for a null-terminated array of 8-bit unsigned characters. 对于C风格的字符串,您可能要使用%s ,这是8位无符号字符的以null终止的数组的格式说明符。

Also, a more straightforward way of converting from a C string to an NSString is by using the + (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc method of the NSString class. 同样,从C字符串转换为NSString的更直接方法是使用NSString类的+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc方法。 See the NSString class reference for more details. 有关更多详细信息,请参见NSString类参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM