Objective-C - 将 NSString 转换为 C 字符串
可能的重复:
objc 警告:“丢弃指针目标类型中的限定符” < /p>
I将 NSString
转换为 C 字符串时遇到了一些麻烦。
const char *input_image = [[[NSBundle mainBundle] pathForResource:@"iphone" ofType:@"png"] UTF8String];
const char *output_image = [[[NSBundle mainBundle] pathForResource:@"iphone_resized" ofType:@"png"] UTF8String];
const char *argv[] = { "convert", input_image, "-resize", "100x100", output_image, NULL };
// ConvertImageCommand(ImageInfo *, int, char **, char **, MagickExceptionInfo *);
// I get a warning: Passing argument 3 'ConvertImageCommand' from incompatible pointer type.
ConvertImageCommand(AcquireImageInfo(), 2, argv, NULL, AcquireExceptionInfo());
另外,当我调试 argv 时,它似乎不正确。我看到这样的价值观:
argv[0] contains 99 'c' // Shouldn't this be "convert"?
argv[1] contains 0 '\100' // and shouldn't this be the "input_image" string?
Possible Duplicate:
objc warning: “discard qualifiers from pointer target type”
I'm having a bit of trouble converting an NSString
to a C string.
const char *input_image = [[[NSBundle mainBundle] pathForResource:@"iphone" ofType:@"png"] UTF8String];
const char *output_image = [[[NSBundle mainBundle] pathForResource:@"iphone_resized" ofType:@"png"] UTF8String];
const char *argv[] = { "convert", input_image, "-resize", "100x100", output_image, NULL };
// ConvertImageCommand(ImageInfo *, int, char **, char **, MagickExceptionInfo *);
// I get a warning: Passing argument 3 'ConvertImageCommand' from incompatible pointer type.
ConvertImageCommand(AcquireImageInfo(), 2, argv, NULL, AcquireExceptionInfo());
Also when I debug argv
it doesn't seem right. I see values like:
argv[0] contains 99 'c' // Shouldn't this be "convert"?
argv[1] contains 0 '\100' // and shouldn't this be the "input_image" string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
理查德是正确的,这是一个使用
strdup
抑制警告。Richard is correct, here is an example using
strdup
to suppress the warnings.该警告是因为您传递了一个
char const **
(指针到指针到 const-char),而 API 需要一个char **
(指针- to-pointer-to-char,特别是以 NULL 结尾的非常量 C 字符串列表)。我的观点是 const 使指针类型不兼容。解决这个问题的安全方法是将 UTF8 字符串复制到非常量 C 字符串缓冲区中;不安全的方法是强制转换。
The warning is because you are passing a
char const **
(pointer-to-pointer-to-const-char) where the API expects achar **
(pointer-to-pointer-to-char, in particular a NULL-terminated list of non-const C strings).My point being the
const
makes the pointer types incompatible. The safe way to get around that is to copy the UTF8 strings into non-const C-string buffers; the unsafe way is to cast.使用 cStringUsingEncoding 或 getCString:maxLength:编码:
Use cStringUsingEncoding or getCString:maxLength:encoding: