Using the C#marshal class to implement managed and unmanaged mutual conversions

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.