Obsolete Marshal.PtrToStructure( ... )

  • Thread starter Thread starter Dev10110110
  • Start date Start date
D

Dev10110110

Guest
I have some related questions about Marshal.PtrToStructure. Thanks for any help.

1. How is PtrToStructure(IntPtr, Object) used? Can I please have a short simple sample? Even though I have no idea how it works, I think I need to use it.

2. Because Marshal.PtrToStructure(...) is obsolete, but Marshal.PtrToStructure<T>(...) isn't, how do I use the latter in my code below? It seems to be impossible, therefore the former should not be made obsolete because there's a use case for it. Am I right?

3. I want a generic struct filler function that fills an arbitrary struct from a binary source (byte stream), is there a better way than what I have? It's slower than it should be because on return of the Fill function the filled data had to be duplicated by the assignment: s1 = (S1) Fill( s1 ). It would be better if the Fill function can work on struct s1 directly rather than having to fill a separate instance.

namespace ConsoleApp1
{
class Program
{
[StructLayout(LayoutKind.Sequential, Pack=1)]
struct S1
{
public byte A;
public UInt16 B;
public UInt32 C;
}


[StructLayout(LayoutKind.Sequential, Pack=1)]
struct S2
{
public byte A;
public UInt32 B;
public UInt64 C;
}


static object Fill( object SomeStruct )
{
byte[] a = new byte[ Marshal.SizeOf( SomeStruct ) ];

for( int i = 0; i < a.Length; i++ )
a = 0; // pretend here we are filling with real data

unsafe
{
fixed( void *p = a )
{
return Marshal.PtrToStructure( (IntPtr) p, SomeStruct.GetType() );
}
}

}


static void Main( string[] args )
{
S1 s1 = new S1(){ A=1, B=2, C=3 };
S2 s2 = new S2(){ A=4, B=5, C=6 };

s1 = (S1) Fill( s1 );
s2 = (S2) Fill( s2 );

Console.WriteLine( "" + s1.A + " " + s1.B + " " + s1.C );
Console.WriteLine( "" + s2.A + " " + s2.B + " " + s2.C );

Console.ReadLine();
}
}
}

Continue reading...
 
Back
Top