在VB.net中如何取变量、结构、数组、函数的地址?

在VB6中可以取变量、结构、数组、函数的地址,那么在VB.net中能不能取到变量、结构、数组等的地址?表示还没接触这门新语言,求详解

当然可以的,需要System.Runtime.InteropServices 命名空间中的 Marshal 类

Imports System.Runtime.InteropServices '这里一定要有 
Public Class Form1
    Public Structure m_Point
        Dim x As Integer
        Dim y As Integer
    End Structure
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer = 50
        Dim ai() As Integer = {1, 2, 3, 4, 5}
        Dim pi As IntPtr = GCHandle.Alloc(i, GCHandleType.Pinned).AddrOfPinnedObject() '取得整形变量的指针 
        Dim pai As IntPtr = GCHandle.Alloc(ai, GCHandleType.Pinned).AddrOfPinnedObject() '取得整形数组首地址指针

        MsgBox(Marshal.ReadInt32(pi, 0)) '读回整形变量指针指向的值
        MsgBox(Marshal.ReadInt32(pai, 0 * 4)) '读回数组的第一个元素
        MsgBox(Marshal.ReadInt32(pai, 1 * 4)) '读回数组的第二个元素
        MsgBox(Marshal.ReadInt32(pai, 2 * 4)) '读回数组的第三个元素

        '-----下面是结构--------------------------
        Dim m_p As New m_Point
        m_p.x = 100
        m_p.y = 50
        Dim pm_p As IntPtr = GCHandle.Alloc(m_p, GCHandleType.Pinned).AddrOfPinnedObject() '取得结构首地址指针 
        MsgBox(Marshal.ReadInt32(pm_p, 0 * 4)) '读回结构的第一个值
        MsgBox(Marshal.ReadInt32(pm_p, 1 * 4)) '读回结构的第二个值
    End Sub
End Class

温馨提示:答案为网友推荐,仅供参考