|
|
test1.cpp
- #include <iconv.h>
- #include <iostream>
- using namespace std;
- int main(){
- char* inbuf=strdup("123456");
- char* outbuf=(char *)malloc(sizeof(char)*10);
- memset(outbuf, 0, 10 );
-
- cout<<"inbuf_before:"<<inbuf<<endl;
- cout<<"outbuf_before:"<<outbuf<<endl;
- // cout<<"&outbuf_before:"<<&outbuf<<endl;
- size_t inbytesleft=strlen(inbuf);
- size_t outbytesleft=10;
- //please take a look following lines
- //start..
- iconv_t cd;
- char **pin = &inbuf;
- char **pout = &outbuf;
-
- cd = iconv_open("utf-8","gbk");
- memset(outbuf,0,outbytesleft);
- iconv(cd,pin,&inbytesleft,pout,&outbytesleft);
- iconv_close(cd);
- //..end
- cout<<"inbuf_after:"<<inbuf<<endl;
- cout<<"outbuf_after:"<<outbuf<<endl;
- // cout<<"&outbuf_after:"<<&outbuf<<endl;
- free(inbuf);
- free(outbuf);
- }
复制代码
test2.cpp
- #include <iconv.h>
- #include <iostream>
- using namespace std;
- void convert(char * inbuf, char* outbuf, size_t inbytesleft, size_t outbytesleft);
- int main(){
- char* inbuf=strdup("123456");
- char* outbuf=(char *)malloc(sizeof(char)*10);
- memset(outbuf, 0, 10 );
-
- cout<<"inbuf_before:"<<inbuf<<endl;
- cout<<"outbuf_before:"<<outbuf<<endl;
- // cout<<"&outbuf_before:"<<&outbuf<<endl;
- size_t inbytesleft=strlen(inbuf);
- size_t outbytesleft=10;
- //please take a look following lines
- //start..
- convert(inbuf, outbuf, inbytesleft, outbytesleft);
- //..end
- cout<<"inbuf_after:"<<inbuf<<endl;
- cout<<"outbuf_after:"<<outbuf<<endl;
- // cout<<"&outbuf_after:"<<&outbuf<<endl;
- free(inbuf);
- free(outbuf);
- }
- //move the convert block to a function.
- void convert(char * inbuf, char* outbuf, size_t inbytesleft, size_t outbytesleft){
- iconv_t cd;
- char **pin = &inbuf;
- char **pout = &outbuf;
-
- cd = iconv_open("utf-8","gbk");
- memset(outbuf,0,outbytesleft);
- iconv(cd,pin,&inbytesleft,pout,&outbytesleft);
- iconv_close(cd);
- }
复制代码
执行结果为:
- # g++ -o test1 test1.cpp
- # ./test1
- inbuf_before:123456
- outbuf_before:
- inbuf_after:
- outbuf_after:
- # g++ -o test2 test2.cpp
- # ./test2
- inbuf_before:123456
- outbuf_before:
- inbuf_after:123456
- outbuf_after:123456
复制代码
其中test2是期望的结果。
可test1的问题在哪呢? |
|