3

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#?

2
  • Can you please look at this link . It talks about how to use Marshal.Copy correctly. Also this one might be useful too. Commented Apr 25, 2011 at 7:13
  • I don't know C# so this might be irrelevant, but pData in the C++ code is treated as a char*, and looks like it's treated as a int* in your C# code. That's two very different things when you do pointer arithmetics. Commented Apr 25, 2011 at 7:17

2 Answers 2

2

.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)...

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

No, can you tell me more details

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.