开发者

trouble using pointers in C#

Let's have a byte array

byte[] Test = { 0, 0, 0, 0 };

I want to do this:

UInt32* p = &Test[0];
p* = 0xAABBCCDD;

or shortly:

(int*)(&Test[0])* = 0xAABBCCDD;

In Delphi I'd do:

PUInt32(@Test[0])^ := $AABBCCDD;

where PUInt32 = ^Uint32 or typdef PUInt32 = *UInt32 in C#.

But don开发者_高级运维't know how it works in C#.


This kind of code is fundamentally unsafe, it defeats the compiler's type system. And won't be accepted by the verifier. If you accidentally declare the array wrong, 3 elements for example, then you'll corrupt memory and produce a very hard to diagnose bug.

This can however also be done safely:

byte[] test = BitConverter.GetBytes(0xaabbccdd);

Which the slight disadvantage that it creates the array for you. Bypassing that requires the unsafe version:

fixed (byte* ptr = test)
{
    *((uint*)ptr) = 0xaabbccdd;
}

Which requires you to use the unsafe keyword in the method declaration and tick the Project + Properties, Build, "Allow unsafe code" option.


you can use pointers in c# with unsafe keyword. http://msdn.microsoft.com/en-us/library/chfa2zb8(v=vs.71).aspx.

But as other suggested not using pointers is much better way.

you should use unsafe:

Real-time applications, we might need to use pointers to enhance performance in such applications. External functions, in non-.net DLLs some functions requires a pointer as a parameter, such as Windows APIs that were written in C. Debugging, sometimes we need to inspect the memory contents for debugging purposes, or you might need to write an application that analyzes another application process and memory.

http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=351

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜