【发布时间】:2016-02-16 06:17:47
【问题描述】:
我试图了解 C# 中的持久内存,但不知道为什么这段代码没有保留对其中一个函数所做的更改。
using System;
using System.Runtime.InteropServices;
public class Test2
{
public struct value
{
public int sz;
}
public static void Main(string[] args)
{
one foo1 = new one(one_full);
two foo2 = new two(two_full);
make_calls(foo1, foo2);
}
public delegate void one(IntPtr ctx);
public static void one_full(IntPtr ctx)
{
/* set sz and see if persists */
GCHandle gch = GCHandle.FromIntPtr(ctx);
value val = (value)gch.Target;
val.sz = 6;
Console.WriteLine("Changed sz to be 6");
}
public delegate void two(IntPtr ctx);
public static void two_full(IntPtr ctx)
{
GCHandle gch = GCHandle.FromIntPtr(ctx);
value val = (value)gch.Target;
Console.Write("sz is = ");
Console.WriteLine(val.sz);
}
public static void make_calls(one f_one, two f_two)
{
value test = new value();
test.sz = 0;
IntPtr ptr = GCHandle.ToIntPtr(GCHandle.Alloc(test));
f_one(ptr);
f_two(ptr);
}
}
我知道它最后缺少 free 但这只会导致混乱的内存管理....我正在寻找是否有人可以帮助我并解释为什么 sz 在第二个函数被调用...
运行时的输出为:
Changed sz to be 6
sz is = 0
【问题讨论】:
标签: c# .net memory persistence ref