Results 1 to 1 of 1

Thread: Disposing members of an instance of an unknown type

Threaded View

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jun 2006
    Posts
    21

    Disposing members of an instance of an unknown type

    This is for a program that has a built-in script system (using CodeDom), and requires the objects that were created by the script to be disposed before updating/re-compiling the script, in order to stop the execution of the older assembly.

    I'm trying to make a generic method to dispose an instance of any class, so that scripters don't need to implement IDisposable.

    Let's say the scripter created a class, with unknown contents, that may not implement IDisposable.
    Like this:
    vb Code:
    1. Public Class foo
    2.     Dim obj1 As New managedType1()
    3.     Dim obj2 As New managedType2()
    4.     Dim var1 As unmanagedType1
    5. End Class

    vb Code:
    1. Dim myFoo As New foo

    How to dispose myFoo?

    I've tried it this way (with a class that has StructLayout attribute):
    vb Code:
    1. Public Shared Sub DisposeObj(ByVal obj As Object)
    2.         If TypeOf obj Is IDisposable Then
    3.             CType(obj, IDisposable).Dispose()
    4.             Exit Sub
    5.         End If
    6.  
    7.         Dim typeOfObj As Type = obj.GetType()
    8.         If typeOfObj.StructLayoutAttribute Is Nothing Then Exit Sub
    9.  
    10.         Dim gch As GCHandle = GCHandle.Alloc(obj)
    11.         Dim offset As Integer
    12.         Dim memberObj As Object
    13.  
    14.         'try to dispose the members of this class
    15.         For Each member As Reflection.MemberInfo In typeOfObj.GetMembers(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.DeclaredOnly)
    16.             offset = Marshal.OffsetOf(typeOfObj, member.Name).ToInt32
    17.             memberObj = GCHandle.FromIntPtr(New IntPtr(GCHandle.ToIntPtr(gch).ToInt32 + offset)).Target
    18.  
    19.             DisposeObj(memberObj)
    20.         Next
    21.     End Sub
    But line 17 returns obj. I know this wasn't even supposed to work, because the offset doesn't tell where the member instance is allocated.

    Any other ideas?
    Last edited by Warwizard; Jun 14th, 2008 at 10:20 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width