gpt4 book ai didi

C# 不安全代码固定指针作为参数传递

转载 作者:太空狗 更新时间:2023-10-29 20:25:15 24 4
gpt4 key购买 nike

我在 msdn 上看到了以下代码:

        unsafe static void SquarePtrParam (int* p) 
{
*p *= *p;
}

unsafe static void Main()
{
Point pt = new Point();
pt.x = 5;
pt.y = 6;
// Pin pt in place:
fixed (int* p = &pt.x)
{
SquarePtrParam (p);
}
// pt now unpinned.
Console.WriteLine ("{0} {1}", pt.x, pt.y);
}

我只是想知道,我们在SquarePtrParam函数中直接访问指针,它是否从调用方法继承了数组固定的信息?

为什么我们不需要在 SquarePtrParam 中显式地在本地将其设置为 fixed

我想我可以对这个 fixed 语句进行一些详细说明。

最佳答案

固定语句以与“using”语句在using(FileStream stream = new FileStream(..))构造中关闭打开的文件相同的方式实现unpin内存区域。内存将被固定,直到您离开固定代码块。

在 IL 代码中,它将创建虚拟 PINNED 局部变量并将指针存储到其中。这将不允许 GC 移动包含此指针的内存区域。在您离开固定 block 后,它会将零存储到此 PINNED 变量中。就像这样:

public static unsafe void TestInternal(byte* pointer)
{
Console.WriteLine((IntPtr)pointer);
}

public static void FixedDemo()
{
Byte[] newArray = new Byte[1024];

unsafe
{
fixed (Byte* pointer = &newArray[0])
{
TestInternal(pointer);
}
}

Console.WriteLine("Test Complete");
}

IL 代码中的 FixedDemo:

.method public hidebysig static void  FixedDemo() cil managed
{
// Code size 47 (0x2f)
.maxstack 2
.locals init ([0] uint8[] newArray,
[1] uint8& pinned pointer)
IL_0000: nop
IL_0001: ldc.i4 0x400 // Put 1024 on the stack
IL_0006: newarr [mscorlib]System.Byte // allocate new array of 1024 length
IL_000b: stloc.0 // Store it in local variable 0
IL_000c: nop
IL_000d: ldloc.0 // Put local variable 0 on the stack
IL_000e: ldc.i4.0 // Put zero on the stack
IL_000f: ldelema [mscorlib]System.Byte // Load address of zero index from array
IL_0014: stloc.1 // !!! Here we pin memory by storing it in pinned variable
IL_0015: nop
IL_0016: ldloc.1 // Load function argument
IL_0017: conv.i // Perform conversion
IL_0018: call void FinMath.Tests.Program::TestInternal(uint8*)
IL_001d: nop
IL_001e: nop
IL_001f: ldc.i4.0 // Load zero on the stack
IL_0020: conv.u // Perform conversion
IL_0021: stloc.1 // !!!! Here we unpin memory
IL_0022: nop
IL_0023: ldstr "Test Complete" // Load string
IL_0028: call void [mscorlib]System.Console::WriteLine(string) // Out message
IL_002d: nop
IL_002e: ret
} // end of method Program::FixedDemo

更多信息请访问:

  1. MSDN

  2. MSDN Magazine: Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework

  3. Common language Runtime standard ECMA 335第三部分,1.1.4.2托管指针(type &)

关于C# 不安全代码固定指针作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8095140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com