0

出于调试原因,我想销毁仍然作为引用的类实例。那可能吗?它不必优雅或稳定,因为这永远不会出现在生产代码中。

澄清:

Public Sub Main
    Dim o as MyClass
    Set o = New MyClass //o is created, one reference
    DestroyObject o     //Class_Terminate is called and the object destroyed
    //Further code, not using o
End Sub                 //Possible runtime error here (don't care)

那可能吗?一种方法是调用IUnknown::Release手动减少引用计数,但是我现在必须多久调用一次呢?

4

2 回答 2

3

这是一个非常糟糕的主意

Option Explicit

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

Private m_oRef As Class1

Private Sub Command1_Click()
    Dim o As Class1

    Set o = New Class1
    Set m_oRef = o
    DestroyObject o
    ' releasing m_oRef after this point will bring down the IDE '
End Sub

Private Sub DestroyObject(pArg As Object)
    Dim lRefCount       As Long
    Dim lIdx            As Long
    Dim pUnk            As IUnknown

    lIdx = ObjPtr(pArg) + &H20
    Call CopyMemory(lRefCount, ByVal lIdx, 4)
    For lIdx = 1 To lRefCount - 2
        Call CopyMemory(pUnk, pArg, 4)
        Set pUnk = Nothing
    Next
    Set pArg = Nothing
End Sub
于 2010-06-01T08:07:24.197 回答
1

如您所知,对象本身会Class_Terminate在它认为其引用计数为零时调用,因此您的调用建议Release应该可以解决问题 - 继续调用Release直到Release它自己抛出错误。

这个来自 Bruce McKinney 的 Hardcore Visual Basic 的页面提出了一种可能的方式,它有时可能会获得引用计数,但我认为你不需要进入那个除非这个方案(Release直到你不能再Release没有)不起作用。

“这永远不会出现在生产代码中”-当然要小心您的假设...

于 2010-06-01T07:39:24.087 回答