Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to access Objects via thier addresses?

Status
Not open for further replies.

happyabc

IS-IT--Management
Mar 10, 2004
164
IN
I want to save the address of an Object in a long and then access it by using another Object variable of the same type but Windows is always closing the app for illegal memory access. The code is similar to:


dim o as New <some-class>
o.<some-property>=123 'say
dim lng as Long
lng = ObjPtr(o)
dim o2 as <some-class>
CopyMemory o2, lng, 4 'Win32 API
debug.Print o2.<some-property> 'expect 123

In a test program I get the error after the function ( main ) executes, but the expected output does appear; on the production program I get on the CopyMemory line itself. What is the correct way to do this?
 
You have to use an interim temporary object because of issues with reference counts against the objects (which are Copymemory does not know anything about). So:
Code:
[COLOR=blue]Option Explicit

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)


Private Sub Command1_Click()
    Dim OriginalObject As Collection
    Dim TemporaryObject As Collection
    Dim lObjectPointer As Long
    Dim TheNewObject As Object
    
    Set OriginalObject = New Collection
    OriginalObject.Add "Hello"
    
    lObjectPointer = ObjPtr(OriginalObject)
    CopyMemory TemporaryObject, lObjectPointer, Len(lObjectPointer)
    Set TheNewObject = TemporaryObject ' get reference to the object with a legit ref count
    CopyMemory TemporaryObject, 0&, 4 ' erase temporary, ref-countless reference to object
    Debug.Print TheNewObject.Item(1)
End Sub
[/color]
 
Its helped partially. The code that I had put up was an abstraction from the real case. It turned out that the abstracted program works even without a temporary object - the problem really lay in not clearing the indirect Object.

However in my actual program, the original object is a local one and has to be accessed indirectly outside that scope. By that time the original object has already been deallocated and so the saved reference becomes invalid and can't be used to initialize an indirect object. To restate what you have pointed out, I need to increase the reference count of the original object as soon as I have saved its address. Could you demonstrate that isolated?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top