SoFunction
Updated on 2025-04-08

Provide SQLite3 with an ANSI to UTF8 intertransfer function

Must use when using Sqlite3

How to use:

char* src = "...";//ANSI or UTF8 string to be converted
char* dst = NULL;//Save memory pointers allocated by the function, and do not need to be passed into the memory buffer.

Convert to UTF-8:to_utf8(src, &dst);
Convert to ANSI:to_gb(src, &dst);

Return value: zero - failed, non-zero - successful.
Note: If the operation is successful, you need to manually free the space allocated internally of the function:

Copy the codeThe code is as follows:

if(dst)
{
    free(dst);
    dst = NULL;
}

Code:

Copy the codeThe code is as follows:

#include <>
#include <>int to_utf8(char* psrc, char** ppdst)
{
    int ret,ret2;
    wchar_t* pws = NULL;
    char* putf = NULL;

    ret = MultiByteToWideChar(CP_ACP, 0, psrc, -1, NULL, 0);
    if(ret<=0){
        *ppdst = NULL;
        return 0;
    }
    pws = (wchar_t*)malloc(ret*2);
    if(!pws){
        *ppdst = NULL;
        return 0;
    }
    MultiByteToWideChar(CP_ACP, 0, psrc, -1, pws, ret);
    ret2 = WideCharToMultiByte(CP_UTF8, 0, pws, -1, NULL, 0, NULL, NULL);
    if(ret2<=0){
        free(pws);
        return 0;
    }
    putf = (char*)malloc(ret2);
    if(!putf){
        free(pws);
        return 0;
    }
    if(WideCharToMultiByte(CP_UTF8, 0, pws, ret, putf, ret2, NULL, NULL)){
        *ppdst = putf;
        free(pws);
        return 1;
    }else{
        free(pws);
        free(putf);
        *ppdst = NULL;
        return 0;
    }
}

int to_gb(char* psrc, char** ppdst)
{
    int ret, ret2;
    wchar_t* pws = NULL;
    char* pgb = NULL;
    ret = MultiByteToWideChar(CP_UTF8, 0, psrc, -1, NULL, 0);
    if(ret<=0){
        *ppdst = NULL;
        return 0;
    }
    pws = (wchar_t*)malloc(ret*2);
    if(!pws){
        *ppdst = NULL;
        return 0;
    }
    MultiByteToWideChar(CP_UTF8, 0, psrc, -1, pws, ret);
    ret2 = WideCharToMultiByte(CP_ACP, 0, pws, -1, NULL, 0, NULL, NULL);
    if(ret2<=0){
        free(pws);
        return 0;
    }
    pgb = (char*)malloc(ret2);
    if(!pgb){
        free(pws);
        *ppdst = NULL;
        return 0;
    }
    if(WideCharToMultiByte(CP_ACP, 0, pws, -1, pgb, ret2, NULL, NULL)){
        *ppdst = pgb;
        free(pws);
        return 1;
    }else{*ppdst = 0;
        free(pgb);
        free(pws);
        return 0;
    }
}

by: Girls don't cry