[英]C# unsafe code fixed pointer passed as parameter
我在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(..))構造中打開的文件相同的方式來實現固定存儲區。 內存將固定,直到您離開固定代碼塊。
在IL代碼中,它將創建虛擬的PINNED局部變量並將指針存儲到該變量中。 這將不允許GC移動內存區域包含此指針。 離開固定塊后,它將零存儲到此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
有關更多信息,請訪問:
通用語言運行時標准ECMA 335分區III,1.1.4.2受管指針(類型&)
它從調用方法繼承數組固定的信息嗎?
不,不需要該信息。 它所知道的就是已經傳遞了一個指針。 獲取指針的一種方法是通過fixed
語句,但是還有其他方法(例如,通過轉換IntPtr),並且任何此類兼容的指針也可以傳遞給SquarePtrParam
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.