回答編集履歴
3
CriticalFinalizerObject を継承すると動かなかった
answer
CHANGED
@@ -54,7 +54,7 @@
|
|
54
54
|
|
55
55
|
```C#
|
56
56
|
[StructLayout(LayoutKind.Sequential)]
|
57
|
-
public unsafe class Example2
|
57
|
+
public unsafe class Example2
|
58
58
|
{
|
59
59
|
int buff;
|
60
60
|
GCHandle gch;
|
2
CriticalFinalizerObject の継承し忘れ
answer
CHANGED
@@ -54,7 +54,7 @@
|
|
54
54
|
|
55
55
|
```C#
|
56
56
|
[StructLayout(LayoutKind.Sequential)]
|
57
|
-
public unsafe class Example2
|
57
|
+
public unsafe class Example2 : CriticalFinalizerObject
|
58
58
|
{
|
59
59
|
int buff;
|
60
60
|
GCHandle gch;
|
1
GCHandle.Alloc を使った方法を追記
answer
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
|
1
|
+
ポインタを外部に公開したいということなら、こんな感じですかね。
|
2
2
|
|
3
3
|
```C#
|
4
4
|
using System;
|
@@ -47,4 +47,43 @@
|
|
47
47
|
}
|
48
48
|
}
|
49
49
|
}
|
50
|
+
```
|
51
|
+
#追記
|
52
|
+
|
53
|
+
何がなんでも変数のポインタを公開したいということであれば GC の移動対象外にする必要があるので、GCHandle.Alloc でクラスをピン止めしてください。
|
54
|
+
|
55
|
+
```C#
|
56
|
+
[StructLayout(LayoutKind.Sequential)]
|
57
|
+
public unsafe class Example2
|
58
|
+
{
|
59
|
+
int buff;
|
60
|
+
GCHandle gch;
|
61
|
+
|
62
|
+
public Example2() {
|
63
|
+
gch = GCHandle.Alloc(this, GCHandleType.Pinned);
|
64
|
+
}
|
65
|
+
|
66
|
+
~Example2()
|
67
|
+
{
|
68
|
+
gch.Free();
|
69
|
+
}
|
70
|
+
|
71
|
+
public int* Buffer {
|
72
|
+
get {
|
73
|
+
fixed (int* ptr = &buff) {
|
74
|
+
return ptr;
|
75
|
+
}
|
76
|
+
}
|
77
|
+
}
|
78
|
+
|
79
|
+
public int Value {
|
80
|
+
get {
|
81
|
+
return buff;
|
82
|
+
}
|
83
|
+
set {
|
84
|
+
buff = value;
|
85
|
+
}
|
86
|
+
}
|
87
|
+
}
|
88
|
+
|
50
89
|
```
|