' Classes/System/Runtime/InteropServices/GCHandle.ab

Namespace System
Namespace Runtime
Namespace InteropServices

Class GCHandle
Public
	Function Target() As Object
		Target = _System_PtrObj(handle)
	End Function

	Sub Target(obj As Object)
		If handle <> 0 Then
			Dim i = allocated.IndexOf(Target())
			'assert(i <> -1)
			allocated[i] = obj
		End If
		allocated.Add(obj)
		handle = ObjPtr(obj)
	End Sub

	Const Function IsAllocated() As Boolean
		Return handle <> 0
	End Function

	Static Function Alloc(obj As Object) As GCHandle
		Alloc = New GCHandle
		Alloc.Target = obj
	End Function

	Sub Free()
		allocated.Remove(Target)
		handle = 0
	End Sub

	Static Function ToIntPtr(h As GCHandle) As LONG_PTR
		Return h.handle As LONG_PTR
 	End Function

	Static Function FromIntPtr(ip As LONG_PTR) As GCHandle
		If ip = 0 Then
			Throw New InvalidOperationException("GCHandle.FromIntPtr: ip is 0.")
		End If
		FromIntPtr = New GCHandle
		FromIntPtr.handle = ip As VoidPtr
	End Function

	Override Function GetHashCode() As Long
		Return _System_HashFromPtr(handle)
	End Function

	Function Equals(y As GCHandle) As Boolean
		Return handle = y.handle
	End Function

	Function Operator == (y As GCHandle) As Boolean
		Return Equals(y)
	End Function

	Function Operator <> (y As GCHandle) As Boolean
		Return Not Equals(y)
	End Function

	Override Function ToString() As String
		Return "System.Runtime.InteropServices.GCHandle"
	End Function

'Private
	Sub GCHandle()
	End Sub

Private
	handle As VoidPtr

	Static allocated = New System.Collections.Generic.List<Object>
End Class

End Namespace 'System
End Namespace 'Runtime
End Namespace 'InteropServices
