iconv source code linux

wget https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.17.tar.gz

交叉编译 libiconv

tar xvf libiconv-1.17.tar.gz
cd libiconv-1.17/
./configure --prefix=$(pwd)/.. --host=arm-linux-gnueabihf
make && make install

生成静态库

./configure --prefix=$(pwd)/.. --host=arm-linux-gnueabihf --enable-static
make -j
find . -type f -name "*.a"

./lib/.libs/libiconv.a
./lib/libcharset.a
./libcharset/lib/.libs/libcharset.a
./srclib/libicrt.a

find . -type f -name "*.so*"

./lib/.libs/libiconv.so.2.6.1
./lib/libcharset.so.1.0.0
./libcharset/lib/.libs/libcharset.so.1.0.0
生成动态库

./configure --prefix=$(pwd)/.. --host=arm-linux-gnueabihf --enable-shared
make -j
find . -type f -name "*.a"

./lib/libcharset.a
./libcharset/lib/.libs/libcharset.a
./srclib/libicrt.a

find . -type f -name "*.so*"

./lib/.libs/libiconv.so.2.6.1
./lib/libcharset.so.1.0.0
./libcharset/lib/.libs/libcharset.so.1.0.0

iconv c++ 转码示例

int utf82gbk(string instr, string& outstr)
{
    iconv_t cd = iconv_open("gbk", "utf-8");
    size_t inbytesleft = instr.length();
    size_t outbytesleft = 3 * inbytesleft;
    char* outbuf = (char*)malloc(outbytesleft);
    memset(outbuf, 0, outbytesleft);
    size_t bytes = outbytesleft;
    char* inbuf = (char*)malloc(inbytesleft);
    memcpy(inbuf, instr.data(), instr.length());

    char* srcstart = inbuf;
    char* tempoutbuf = outbuf;

    int ret = iconv(cd, &srcstart, &inbytesleft, &tempoutbuf, &outbytesleft);
    if (ret < 0)
    {
        perror("iconv");
        free(inbuf);
        free(outbuf);
        return -1;
    }
    bytes -= outbytesleft;
    iconv_close(cd);
    outstr.assign((char*)outbuf, bytes);
    free(inbuf);
    free(outbuf);

    return 0;
}

int gbk2utf8(string instr, string& outstr)
{
    iconv_t cd = iconv_open("utf-8", "gbk");
    size_t inbytesleft = instr.length();
    size_t outbytesleft = 3 * inbytesleft;
    char* outbuf = (char*)malloc(outbytesleft);
    memset(outbuf, 0, outbytesleft);
    size_t bytes = outbytesleft;
    char* inbuf = (char*)malloc(inbytesleft);
    memcpy(inbuf, instr.data(), instr.length());

    char* srcstart = inbuf;
    char* tempoutbuf = outbuf;

    int ret = iconv(cd, &srcstart, &inbytesleft, &tempoutbuf, &outbytesleft);
    if (ret < 0)
    {
        perror("iconv");
        free(inbuf);
        free(outbuf);
        return -1;
    }
    bytes -= outbytesleft;
    iconv_close(cd);
    outstr.assign((char*)outbuf, bytes);
    free(inbuf);
    free(outbuf);

    return 0;
}
本文链接地址:https://const.net.cn/712.html

标签: none

添加新评论