S
Sharon
Hello Gurus,
I have a function that copy data from byte[] to class as follow:
public static void CopyByteToHeader(Header target, byte[] source)
{
ntPtr pHeaderTarget = Marshal.AllocHGlobal(HEADER_SIZE);
arshal.Copy(source, 0, pHeaderTarget, HEADER_SIZE);
arshal.PtrToStructure(pHeaderTarget, target);
}
public const int HEADER_SIZE = 9;
[StructLayout(LayoutKind.Sequential)]
public class Header
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public byte[] m_type;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] m_lMsgIndex;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] m_lLength;
}
The function works fine. BUT:
This function is executed many times, so it makes a lot of memory copeing.
I want to optimize it doing like in C++:
Public CPP_CopyByteToHeader(Header* target, byte* source)
{
target = (Header*)source
}
This way I’m avoiding the copy.
But is C# I tried:
public static void CopyByteToHeader(Header target, byte[] source)
{
unsafe
{
fixed (byte* pSource = (byte[])source)
{
// Now I need the pointer for the target.
// But I can’t find how to!
}
}
}
As you can see its incomplete. I need to get a pointer to the target.
Can anybody show me how can I do the coply like, like it’s done in the C++
above?
I have a function that copy data from byte[] to class as follow:
public static void CopyByteToHeader(Header target, byte[] source)
{
ntPtr pHeaderTarget = Marshal.AllocHGlobal(HEADER_SIZE);
arshal.Copy(source, 0, pHeaderTarget, HEADER_SIZE);
arshal.PtrToStructure(pHeaderTarget, target);
}
public const int HEADER_SIZE = 9;
[StructLayout(LayoutKind.Sequential)]
public class Header
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public byte[] m_type;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] m_lMsgIndex;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] m_lLength;
}
The function works fine. BUT:
This function is executed many times, so it makes a lot of memory copeing.
I want to optimize it doing like in C++:
Public CPP_CopyByteToHeader(Header* target, byte* source)
{
target = (Header*)source
}
This way I’m avoiding the copy.
But is C# I tried:
public static void CopyByteToHeader(Header target, byte[] source)
{
unsafe
{
fixed (byte* pSource = (byte[])source)
{
// Now I need the pointer for the target.
// But I can’t find how to!
}
}
}
As you can see its incomplete. I need to get a pointer to the target.
Can anybody show me how can I do the coply like, like it’s done in the C++
above?