C语言libiconv编程,libiconv字符集转换库在C#中的使用
《libiconv字符集轉(zhuǎn)換庫使用方法》一文中說到了libiconv可以實(shí)現(xiàn)不同字符集的轉(zhuǎn)換。比如GBK轉(zhuǎn)BIG5等。在項(xiàng)目中因?yàn)樾枰?#xff0c;找到這個庫。可是這個庫在C#中沒有很好的支持。不過,想著既然是C++的庫,那只要動態(tài)加載DLL的接口就好了。可是調(diào)用并不順利,傳進(jìn)去的IntPtr或者byte數(shù)組總是拿不到數(shù)據(jù)。后面回到了C++的方式去調(diào)用,幾經(jīng)調(diào)試,總算找到了原因。
是iconv接口在轉(zhuǎn)換完成后,指針的位置往后移了。而在C#中調(diào)用DLL后回來的指針,已經(jīng)是移動后的,所以拿不到所要的數(shù)據(jù)。
經(jīng)過多種嘗試,沒有辦法將指針移回到原位。
后來,通過C++的二次封裝,在C++中將指針的位置移到了原來的位置,再用C#來調(diào)用,總算達(dá)到了目的。
#include
//包函 libiconv庫頭文件
#include "iconv.h"
//導(dǎo)入 libiconv庫
#pragma comment(lib,"libiconv.lib")
using namespace std;
#define DLL_EXPORT extern "C" __declspec(dllexport)
DLL_EXPORT int ChangeCode( const char* pFromCode,
const char* pToCode,
const char* pInBuf,
size_t* iInLen,
char* pOutBuf,
size_t* iOutLen )
{
size_t outLenTemp=*iOutLen;
iconv_t hIconv = iconv_open( pToCode, pFromCode );
if ( -1 == (int)hIconv )
{
return ?-100;//打開失敗,可能不支持的字符集
}
//開始轉(zhuǎn)換
int iRet = iconv( hIconv, (const char**)(&pInBuf), iInLen, (char**)(&pOutBuf), iOutLen );
if (iRet>=0)
{
pOutBuf=pOutBuf-(outLenTemp-*iOutLen);//轉(zhuǎn)換后pOutBuf的指針被移動,必須移回到起始位置
}
else
{
iRet=-200;
}
//關(guān)閉字符集轉(zhuǎn)換
iconv_close( hIconv );
return iRet;
}
C#調(diào)用的部分
///
/// 字符器轉(zhuǎn)換.
/// 每次轉(zhuǎn)換都需要打開轉(zhuǎn)換器、字符集轉(zhuǎn)換、關(guān)閉轉(zhuǎn)換器。
///
/// 源字符集編碼
/// 目標(biāo)字符集編碼
/// 待轉(zhuǎn)換的內(nèi)容
/// 待轉(zhuǎn)換的長度。轉(zhuǎn)換成功后,將變成0.
/// 轉(zhuǎn)換后的內(nèi)容
/// 轉(zhuǎn)換長度。轉(zhuǎn)換成功后,將變成原值減去轉(zhuǎn)換后的內(nèi)容所占空間的長度
///
[DllImport("CharsetConvert.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ChangeCode(string pFromCode,
string pToCode,
byte[] pInBuf,
ref int iInLen,
byte[] pOutBuf,
ref int iOutLen);
private void buttonOneConvert_Click(object sender, EventArgs e)
{
string toCode = "BIG5";
string fromCode = "GBK";
string inStr = "國k";
byte[] inBuf = Encoding.Default.GetBytes(inStr);
byte[] outBuf = new byte[100];
int inLen = inBuf.Length;
int outLen = outBuf.Length;
int result = CharsetConvter.ChangeCode(fromCode, toCode, inBuf, ref inLen, outBuf, ref outLen);
if (result < 0)
{
MessageBox.Show("轉(zhuǎn)換失敗");
}
else
{
String outStr = Encoding.GetEncoding("BIG5").GetString(outBuf);
MessageBox.Show(outStr);
}
}
總結(jié)
以上是生活随笔為你收集整理的C语言libiconv编程,libiconv字符集转换库在C#中的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过mvn dependency:tre
- 下一篇: C# winForm 定时访问PHP页面