I have a Unicode UChar * string and I need to print it to the console. I used this method

char* UChar_print(const UChar *s, UErrorCode *status, int32_t resultlength)
{

 UConverter *conv;
    char *target=NULL;
    target= malloc(sizeof(UChar) *resultlength );
    int32_t len;
    UErrorCode errorCode;

    errorCode=U_ZERO_ERROR;
    conv = ucnv_open("conv", &errorCode);

    len = ucnv_fromUChars(conv, target, 30000, s, resultlength, &errorCode);
    printf("res %s", target);

    ucnv_close(conv);
    return target;
}

I don't get correct output. Does anyone tried ucnv_fromUChars before ? Or knows how to print the UTF-8 UChar string?

有帮助吗?

解决方案

The main problem with your code is that you used "conv" as converter name. You should use a valid name. See the ICU converter explorer. If your terminal doesn't support Unicode, you should handle conversion errors with an error callback set with ucnv_setFromUCallBack.

Then the calculation of the target buffer size was wrong.

Try something like that (untested):

UErrorCode UChar_print(const UChar *s, int32_t resultlength)
{
    UErrorCode errorCode = U_ZERO_ERROR;

    // Converting to ASCII, or whatever your terminal supports.
    UConverter *conv = ucnv_open("ASCII", &errorCode);
    // You forgot to check whether uconv_open succeeded.
    if (conv == NULL) return errorCode;

    // Compute target capacity as recommended in the ICU reference.
    // Alternatively, you could pre-flight the conversion to get the
    // actual buffer size needed.
    int32_t targetCap = UCNV_GET_MAX_BYTES_FOR_STRING(resultlength,
                                                      ucnv_getMaxCharSize(conv));
    char *target = malloc(targetCap);
    // Here you should check whether the allocation failed.

    // Pass the actual target buffer size, not some arbitrary number. 
    ucnv_fromUChars(conv, target, targetCap, s, resultlength, &errorCode);

    if (errorCode == U_ZERO_ERROR) {
        printf("res %s", target);
    }

    // Don't forget to free the result.
    free(target);

    ucnv_close(conv);

    return errorCode;
}

其他提示

Here are some helper functions that I use, taking advantage of ICU's conversion functions. Hope they might come in useful.

const char* icustring2char(icu::UnicodeString convertme) {
    std::string result;
    convertme.toUTF8String(result);
    return result.c_str();
}

const char* icuchar2char(UChar convertme) {
    icu::UnicodeString temp(convertme);
    return icustring2char(temp);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top