Marshal class Namespace: System.Runtime.InteropServices provides a set of methods for allocating unmanaged memory, copying unmanaged memory blocks, converting managed types to unmanaged types, Other miscellaneous methods that are used when interacting with unmanaged code are also provided. Defined in the Marshal class.Staticmethod is critical for handling unmanaged code. Most of the methods defined in this class are typically used by developers who need to bridge between the managed and unmanaged programming models. For example, the StringToHGlobalAnsi method copies the ANSI characters from the specified string (in the managed heap) to a buffer in the unmanaged heap. The method also allocates the correct size of the target heap. Mutual transformation of struct and IntPtr: Tagcaptureframe F= (tagcaptureframe) marshal.ptrtostructure (M.wparam,typeof(Tagcaptureframe)); struct and byte[] conversions (implemented with the Marshal Class) are reproduced from: http://www.cnblogs.com/tuyile006/archive/2006/12/28/605962.htmlequivalent to serialization and deserialization, but without the use of external files1, struct converted to byte[]Static byte[] Structtobytes (Objectstructobj) { intSize =marshal.sizeof (structobj); INTPTR Buffer=Marshal.allochglobal (size);Try{marshal.structuretoptr (structobj, buffer,false); byte[] bytes =New byte[size]; Marshal.Copy (buffer, Bytes,0, size); returnbytes;} finally{marshal.freehglobal (buffer);}} 2、byte[] Convert to structStatic ObjectBytestostruct (byte[] bytes, Type strcuttype) { intSize =marshal.sizeof (Strcuttype); INTPTR Buffer=Marshal.allochglobal (size);Try{marshal.copy (bytes,0, buffer, size); returnmarshal.ptrtostructure (buffer, strcuttype);} finally{marshal.freehglobal (buffer);}}
Using the C#marshal class to implement managed and unmanaged mutual conversions