c ++到VB.Net IntPtr字符串

时间:2012-06-15 05:18:26

标签: c++ vb.net com marshalling intptr

好吧所以我有这个代码,我将它传递给一个非托管的dll,我只知道导出,并有一些示例代码。我正在找回正确的字符串,但后面跟着垃圾字节。

我基本上是从没有此问题的c ++示例程序中逐字翻译代码。我认为这里有一些基本的东西,所以如果有人能告诉我那是什么,我会很感激。

示例C ++代码

void CDUKPT_TESTDlg::OnButton4() 
{
    // TODO: Add your control notification handler code here
    unsigned char dataout[1024],tmp[1024],ksn[20],keyval[20];
    int nRet,len;
    memset(dataout,0,sizeof(dataout));
    memset(ksn,0,sizeof(ksn));
    memset(keyval,0,sizeof(keyval));
    memset(tmp,0,sizeof(tmp));
    UpdateData(TRUE);

    two_one((unsigned char *)m_strCURKSN.GetBuffer(m_strCURKSN.GetLength()),m_strCURKSN.GetLength(),ksn);
    two_one((unsigned char *)m_strMACK.GetBuffer(m_strMACK.GetLength()),m_strMACK.GetLength(),keyval);
    two_one((unsigned char *)m_EncryptDat.GetBuffer(m_EncryptDat.GetLength()),m_EncryptDat.GetLength(),dataout);

    len=m_EncryptDat.GetLength()/2;
    //extern int __stdcall ExtractDat(unsigned char *input,
    //unsigned short len,unsigned char *output,unsigned char *key,
    //unsigned char *ksn);
    nRet=ExtractDat(dataout,len,tmp,keyval,ksn); //External Call
    //Good string+bad trailing data comes back in tmp
    m_Result=tmp;
    UpdateData(FALSE);
}

此代码会吐出此܉Òdÿo 

这是我的VB.Net代码

Public Function Encrypt(ByVal inp As String) As String
    Dim tmpSB As New StringBuilder
    Dim i As Integer
    Dim tKsn As Char() = TwoOne(StrCurKsn)
    For i = tKsn.Length To 19
        tKsn = tKsn + Chr(0)
    Next
    Dim tMack As Char() = TwoOne(StrMack)
    For i = tMack.Length To 19
        tMack = tMack + Chr(0)
    Next
    Dim tEnc As Char() = TwoOne(inp)
    For i = tEnc.Length To 1023
        tEnc = tEnc + Chr(0)
    Next
    Dim len As Integer = tEnc.Length / 2

    Dim tmpStr(1023) As Char
    Array.Clear(tmpStr, 0, 1024)
    Dim tmpPtr = Marshal.StringToHGlobalAnsi(tmpStr)

    Dim nRet = ExtractDat(tEnc, len, tmpPtr, tMack, tKsn)

    tmpStr = Marshal.PtrToStringAnsi(tmpPtr)
    Dim tsl = tmpStr.Length
    Encrypt = tmpStr
End Function

此代码吐出

܉Òdÿo ålUäÙålUäÙålUäÙålUäÙålUäÙålUäÙålUäÙ

所以我得到了正确的字符串,但后面是重复的垃圾字符串。 我希望我在这里做了一些明显错误的事情,但我已经尝试将数据拉成字节,字符,并在许多不同的方法中转换,我似乎无法摆脱这些字符...... ,ExtractDat不返回字符串的长度(不是问题,因为它不应该,这真的很烦人)。

1 个答案:

答案 0 :(得分:0)

原来这个dll很糟糕,所以在我从供应商那里得到一个新的编译之后它似乎有效。