Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C++ code to C#

Tags:

c++

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

like image 996
user348173 Avatar asked Feb 11 '26 20:02

user348173


2 Answers

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

like image 85
Simon Mourier Avatar answered Feb 14 '26 12:02

Simon Mourier


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

like image 30
NickD Avatar answered Feb 14 '26 13:02

NickD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!