VB.net memory pointers and unmanaged memory applications

Source: Internet
Author: User


Visual Basic never manipulates pointers and raw memory as flexibly as in C or C + +. Use however. NET framework of structures and classes, can do a lot of similar things. They include INTPTR, Marshal and GCHandle. These structures (structs) and classes (classes) allow you to interact in both managed and unmanaged environments. This article will show you how to use these structures and classes to complete pointers and memory operations.

about the INTPTR structure

The INTPTR structure behaves like an integer pointer so that it can be applied to a dedicated platform. This structure can be applied to languages that support or do not support pointers. The. NET file IO class uses this structure to extend the operation file handle. The INTPTR structure behaves like an integer pointer, but it does not have the ability to write or read the corresponding location memory. Then you need to System.Runtime.InteropServices the Marshal class in the namespace.

about the Marshal class

This class provides full allocation of unmanaged memory, copies of unmanaged memory blocks, and methods for converting managed to unmanaged types. Make sure your code is imported into the System.Runtime.InteropServices .

about the GCHandle structure

The GCHANDLE structure provides a way to handle managed objects from unmanaged memory. You can control garbage collection when it is used by unmanaged code.

integer value (read) and (write)

In our first example, we use the Marshal class to store an integer in memory, get a memory pointer to its location in memory, and coexist in a INTPTR structure. Eventually we will use the Marshal class to read back this value.

Here we declare a INTPTR type, and use the AllocHGlobal sharing method in the Marshal class to allocate a 4-byte memory from the global heap and return its address, stored in the INTPTR variable. Next we use the WriteInt32 method in the Marshal class to write the integer value into memory.

Dim ptr as IntPtr : Dim n as Integer = 123

TR = Marshal. AllocHGlobal (4) ' dividing 4 bytes of memory space in the unmanaged memory of the process

Marshal. WriteInt32 (PTR, N) ' writes a 32-bit signed integer into the Divided memory space

The return value of the Marshal.allochglobal method is: A pointer to the newly allocated memory. You must use the Marshal.freehglobal method to release the divided memory after it is exhausted

In the following way, you can read the number of memory in the specified location.

Dim myInt as Integer = Marshal. ReadInt32 (PTR) ' parameter ptr is a memory space pointer

The return value of the Marshal.allochglobal method is: The data value in the memory space

string (read) and (write)

In this example, we write a managed string into the heap and then read it out.

Dim str as string = "Hello World" string is a reference type, so it is stored on the managed heap
Dim ptr as IntPtr = Marshal. Stringtohglobalauto (str) ' copy managed content to unmanaged memory and convert to ANSI format
Dim mystring as String = Marshal. Ptrtostringauto (PTR) ' copy a number of characters from a string stored in unmanaged memory to managed memory

Here, we use the Stringtohglobalauto () method in the Marshal class to copy the managed string into unmanaged memory. We save the memory address in the INTPTR structure. In order to read back the string from the specified memory location, we use the Ptrtostringauto () method in the Marshal class.

Structure Reading and writing

In the next example, we will see how to use the Marshal class and the INTPTR structure for structure reading and writing. Public Structure Point Dim x As Integer Dim y As Integer End Structure Dim mystruct1,mystruct2 As Point MyStruct ure.x=100 mystructure.y=200 Dim ptr as IntPtr = Marshal.allochglobal (marshal.sizeof (mystruct)) marshal.structuretopt R (MyStruct, PTR, True) mystruct2 = Marshal.PtrToStructure (PTR, New point (). GetType)

Here we use a structure called point. This code is similar to Example 1, but note that we used the sizeof method in the Marshal class to return the size of the structure variable. Method StructureToPtr receives the structure variable to be written, a IntPtr instance is returned, indicating whether the Marshal class should call the Destroystructure method, the recommended token is True, and a memory leak can result if marked false. Finally we use Marshal PtrToStructure method to the value of the structure.

Read and Write objects

Now we know how to read and write value types with the marshal and IntPtr classes. Managed objects are handled slightly differently. You need to use GCHandle to read and write these objects, and the following code shows how to do this: public Class Employee public Name as String public Salary as Decimal End Cla SS Dim gh As GCHandle Dim emp as New Employee EMP. Name = "John" emp. Salary = 12345.67 gh = gchandle.alloc (EMP) Dim emp2 as Employee = gh. Target GH. Free ()

Here, for the employee class we use the GCHandle (fragmented phone handle) class to allocate and free memory. The shared (static) Alloc method accepts an object and stores it in memory and an instance of the GCHandle class. We can use this object's target property to point to the object's reference. We can use the free method of the GCHandle instance to destroy the corresponding memory.


Using pointers and unmanaged operations in vb.net is not easy, however IntPtr, GCHandle structures, and Marshal classes allow you to do something similar.

Bipin Joshi
The owner of Bipin Joshi Binaryintellect Consulting, where he provided many training programs on. NET technology.

VB.net memory pointers and unmanaged memory applications

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.