日期:2014-05-18  浏览次数:20931 次

怎样处理DLL中char*类型参数的内容?
1.DLL原形:
    int   __stdcall   _ReadCard(char   *S); //读卡

2.
在DELPHI调用返回:
{182,193,191,168,202,167,176,220,161,163, 'E ', 'r ', 'r ', 'o ', 'r ', ': ', '- ', '2 ', '2 ',0}
显示:读卡失败。Error:-22

3.
在vs2005+C#调用:
[DllImport( "LsdSle4442.dll ",   SetLastError   =   true,   CharSet   =   CharSet.Ansi,   CallingConvention   =   CallingConvention.StdCall)]
                public   static   extern   Int32   _ReadCard(byte[]   S);

    private   void   btnRead_Click(object   sender,   EventArgs   e)
    {
                        byte[]   buf;
                        buf   =   new   Byte[255];
                        int   n   =   _ReadCard(buf);
                        string   s   =   Encoding.ASCII.GetString(buf);

                        MessageBox.Show(s);
    }
中buf返回:
{182,193,191,168,202,167,176,220,161,163,69,114,114,111,114,58,45,50,50,0,...}
显示:??????????Error:-22

问:既然得到了正确的数据,我怎样才能让它显示为:读卡失败。Error:-22


------解决方案--------------------
using System.Text;
using System.Windows.Forms;

class Program
{
static void Main()
{
byte[] buf = {182,193,191,168,202,167,176,220,161,163,69,114,114,111,114,58,45,50,50,0,};
string s = Encoding.GetEncoding( "GB2312 ").GetString(buf);
MessageBox.Show(s);
}
}

// 显示:读卡失败。Error:-22

------解决方案--------------------
string s = Encoding.GetEncoding( "GB2312 ").GetString(buf);

这一句换成

string s = Encoding.Default.GetString(buf);
用系统默认的字符集来解码,不要固定为GB2312,这样以后如果要移植在非中文的系统上减少麻烦。