VarPtr

If anyone knows the replacement function or method for varptr (vb6) in vb 2005 please let me know.


Answer this question

VarPtr

  • Sajeesh

    http://www.google.com.au/search hl=en&safe=off&q=varptr+.net&meta=

    More specifically

    http://www.codeproject.com/vb/net/singleinstance.asp

    has this:


    <P>There are two operations required - set the <CODE lang=vbnet>lpData</CODE>
    member to point to a <CODE lang=vbnet>String</CODE>, and retrieve a <CODE lang=vbnet>String</CODE> from it. In VB6, you would use <CODE
    lang=vb>VarPtr</CODE> and the <CODE lang=vbnet>RtlMoveMemory</CODE> API (a.k.a.
    <CODE lang=vbnet>CopyMemory</CODE>) to do this. In .Net, <CODE
    lang=vbnet>VarPtr</CODE> no longer exists, but the <CODE
    lang=vbnet>Marshal</CODE> class provides much better alternatives.</P>
    <P>To set the pointer to the value of a <CODE lang=vbnet>String</CODE>:</P><PRE lang=vbnet>'//Get an array of bytes for the string
    Dim B() As Byte = Encoding.Default.GetBytes(StringVarToSend)

    Try
    '//Allocate enough memory on the global heap
    Dim lpB As IntPtr = Marshal.AllocHGlobal(B.Length)

    '//Copy the managed array to the un-managed pointer
    Marshal.Copy(B, 0, lpB, B.Length)

    Dim CD As COPYDATASTRUCT
    With CD
    .dwData = 0
    .cbData = B.Length

    '//The ToInt32 function converts an IntPtr to an Integer pointer
    .lpData = lpB.ToInt32
    End With

    'Do something with CD here...

    Finally
    '//Clean up
    Erase B
    Marshal.FreeHGlobal(lpB)
    End Try
    </PRE>
    <P>To retrieve a <CODE lang=vbnet>String</CODE>
    from the pointer:</P><PRE lang=vbnet>Dim B() As Byte
    Try
    '//Get the COPYDATASTRUCT from the message
    Dim CD As COPYDATASTRUCT = m.GetLParam(GetType(COPYDATASTRUCT))

    '//Allocate enough space in B
    ReDim B(CD.cbData)

    '//Create an IntPtr from the Integer pointer
    Dim lpData As IntPtr = New IntPtr(CD.lpData)

    '//Copy the data into the array
    Marshal.Copy(lpData, B, 0, CD.cbData)

    '//Get the string from the Byte Array
    Dim strData As String = Encoding.Default.GetString(B)

    '//Do something with the String here...

    Finally
    '//Clean up
    Erase B
    End Try
    </PRE>



  • VarPtr