Tuesday, December 16, 2008

[vb6] Get the reference count on a VB Class object

The reference count on COM objects, including VB Class objects, are managed by Visual Basic and there is normally no reason to know about it. However, when debugging code involving class objects, it is often useful to read the reference count on an object. The function below returns the reference count, and uses the CopyMemory API and the hidden VB function ObjPtr to retrieve the address of the class object.
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(dest As Any, src As Any, ByVal nbytes As Long)

Private Function GetRefCount(obj As IUnknown) As Long
If obj Is Nothing Then Exit Function
CopyMemory GetRefCount, ByVal (ObjPtr(obj)) + 4, 4
GetRefCount = GetRefCount - 2
End Function

No comments:

Post a Comment