Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created November 17, 2017 11:07
Show Gist options
  • Save ufcpp/b4f4eb02ec8c6c86eb4d84b206c3a2e0 to your computer and use it in GitHub Desktop.
Save ufcpp/b4f4eb02ec8c6c86eb4d84b206c3a2e0 to your computer and use it in GitHub Desktop.
GCHandle の値、どこかのスロットのアドレスがたぶん帰ってきてる。かつ、Free したスロットは即座に再利用されてる
using System;
using System.Runtime.InteropServices;
class X { }
class Y { }
public class Program
{
static void Main()
{
var ptr1 = GCHandle.ToIntPtr(GCHandle.Alloc(new X(), GCHandleType.Normal));
GCHandle.FromIntPtr(ptr1).Free();
// Free 直後に別のオブジェクトを Alloc
var ptr2 = GCHandle.ToIntPtr(GCHandle.Alloc(new Y(), GCHandleType.Normal));
// 同じ値 = スロット的なもの使いまわしてる
Console.WriteLine((long)ptr1);
Console.WriteLine((long)ptr2);
// ptr1 (Free 済み)の方からオブジェクトを復元できるけど、中身はもう ptr2 の方のやつ
// Y って表示される。
Console.WriteLine(GCHandle.FromIntPtr(ptr1).Target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment