[英]How can I convert an NSString to a CString in c++ without Obj-C code?
I am trying to get the current user name in c++ using the NSFullUserName
function but it returns an NSString
. 我正在尝试使用
NSFullUserName
函数获取c ++中的当前用户名,但它返回一个NSString
。 Therefore, how can I convert an NSString
to a CString
in c++ without Obj-C code? 因此,如何在没有Obj-C代码的情况下将c ++中的
NSString
转换为CString
?
It is sheer silliness not to use Objective-C for this. 不为此使用Objective-C是非常愚蠢的。
That said, you can cast an NSString *
to a CFStringRef
and use the CFString
functions to get a C string. 也就是说,您可以将
NSString *
CFStringRef
转换为CFStringRef
并使用CFString
函数来获取C字符串。 You will probably find the CFStringGetLength
and CFStringGetCString
functions and the kCFStringEncodingUTF8
constant useful. 您可能会发现
CFStringGetLength
和CFStringGetCString
函数以及kCFStringEncodingUTF8
常量很有用。 Keep in mind that many Unicode characters require more than one byte to represent in UTF-8. 请记住,许多Unicode字符需要多个字节才能以UTF-8表示。
NSString
is toll-free bridged with CFString
(ie, you can just cast the pointer — the thing it points to can be interpreted as either type), and you can manipulate CFString
using vanilla C calls. NSString
与CFString
是免费的桥接(即,您可以只转换指针-它指向的对象可以解释为任何一种类型),并且可以使用普通C调用来操纵CFString
。
So you'd typically attempt CFStringGetCStringPtr
to try to get a pointer directly to the NSString
contents as a C string without any copying, then fall back on allocating a suitably sized C-style array and CFStringGetCString
if the direct pointer isn't available (typically because the encoding you want doesn't match the NSString
's internal encoding). 因此,您通常会尝试
CFStringGetCStringPtr
尝试以C字符串的形式直接获取指向NSString
内容的指针,而不进行任何复制,然后在没有直接指针的情况下(适当地, CFStringGetCString
使用大小合适的C样式数组和CFStringGetCString
分配)(通常因为您想要的编码与NSString
的内部编码不匹配)。
CFStringGetMaximumSizeForEncoding
will return the maximum size of buffer you need to allocate for a given encoding and string length, CFStringGetLength
the length of a given string. CFStringGetMaximumSizeForEncoding
将返回您需要为给定的编码和字符串长度分配的最大缓冲区大小, CFStringGetLength
为给定的字符串长度。
So eg 所以例如
void Class::DoSomethingWithObjCString(NSString *objcString)
{
CFStringRef string = (CFStringRef)objcString;
const char *bytes = CFStringGetCStringPtr(string, kCFStringEncodingUTF8);
if(bytes)
DoSomethingWithUTF8String(bytes);
else
{
size_t sizeToAllocate =
CFStringGetMaximumSizeForEncoding(
CFStringGetLength(string), kCFStringEncodingUTF8);
char *allocatedBytes = new char[sizeToAllocate];
CFStringGetCString(string,
allocatedBytes,
sizeToAllocate,
kCFStringEncodingUTF8);
DoSomethingWithUTF8String(allocatedBytes);
delete[] allocatedBytes;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.