iOS NSString 与const wchar_t的相互转换

由于项目中需要将nsstring 转化为 const wchar_t *的对象, 第一次在转换的时候的采用的是

+(const wchar_t*)stingTowWchar_t:(NSString*)string

{    const char *cString=[string cStringUsingEncoding:NSUTF8StringEncoding];

//    cString = [ StringUsingEncoding:NSUTF8StringEncoding];

    setlocale(LC_CTYPE, "UTF-8");

    NSInteger iLength = mbstowcs(NULL, cString, 0);

    NSInteger bufferSize = (iLength+1)*sizeof(wchar_t);

    wchar_t *stTmp = (wchar_t*)malloc(bufferSize);

    memset(stTmp, 0, bufferSize);

    mbstowcs(stTmp, cString, iLength);

    stTmp[iLength] = 0;

    printf("begin %ls\n",stTmp);

    std::wstring wstr(stTmp);

    free(stTmp);

    return stTmp;

}

借助于const char , 然后在逐字转换, 经过验证发现, 这种处理, 英文, 可以, 中文不行,最终get到的方案

+(const wchar_t*)stingTowWchar_t:(NSString*)string

{

return (wchar_t*)[string cStringUsingEncoding:NSUTF32StringEncoding];

}

+(NSString*)getStringFromWChar:(const wchar_t*) inStr

{

    setlocale(LC_CTYPE, "UTF-8");

NSInteger strLength = wcslen(inStr);

    NSInteger bufferSize = (strLength+1)*4;

    char *stTmp = (char*)malloc(bufferSize);

    memset(stTmp, 0, bufferSize);

    wcstombs(stTmp, inStr, strLength);

    NSString* ret = [[NSString alloc] initWithBytes:stTmp length:strlen(stTmp) encoding:NSUTF8StringEncoding];//ARC

    free(stTmp);

    return ret;

}

至此, 转换和读取完成, over , 感谢GSDN博主hhh901119!

你可能感兴趣的:(iOS NSString 与const wchar_t的相互转换)