user348173
user348173

Reputation: 9288

Convert C++ code to C#

I have code wrote on C++:

    char szTempString[1500];
    DWORD dwDataLength = PacketBuffer.m_Length - (sizeof(ether_header) + pIpHeader->ip_hl*4 + pTcpHeader->th_off*4);
    PCHAR pData = (PCHAR)pEthHeader + (sizeof(ether_header) + pIpHeader->ip_hl*4 + pTcpHeader->th_off*4);

    // If packet contains any data - process it
    if (dwDataLength)
    {
        //
        // Copy packet payload into the temporary string
        //
        memcpy (szTempString, pData, dwDataLength);         

C#:

char[] szTempString = new char[1500];
var dwDataLength = (int)PacketBuffer.m_Length -
(Marshal.SizeOf(typeof (ETHER_HEADER)) + (pIpHeader->IPLenVer & 0xF)*4 + (pTcpHeader->Off & 0xF)*4);

var pData = (IntPtr)pEthHeader + (Marshal.SizeOf(typeof(ETHER_HEADER)) +
(pIpHeader->IPLenVer & 0xF) * 4 + (pTcpHeader->Off & 0xF) * 4);

if(dwDataLength != 0)
{
    Marshal.Copy(pData,szTempString, 0, dwDataLength);
    Console.WriteLine(szTempString);
}

ehter_header, pIp_header and other is structs, they are converted to C#. The var szTempString contains strange data. Have I converted the pData and function memcpy properly?
Thanks.
PS. This is WinPkFilter library. Maybe somebody used it in C#?

Upvotes: 3

Views: 702

Answers (2)

Simon Mourier
Simon Mourier

Reputation: 139296

.NET's char is actually unicode, not like in c++. You should at least replace char by byte. Then, when you ultimately want a string from bytes, use the Encoding class, like this: Encoding.Default.GetString(bytes)...

Upvotes: 2

NickD
NickD

Reputation: 2646

have you added a [StructLayout(LayoutKind.Sequential, Pack=1)] before your struct?

Upvotes: 1

Related Questions