添加偏移的IntPtrIntPtr

2023-09-02 01:42:28 作者:月寻

我在寻找一种方法,在特定的C#或.NET执行的指针操作。

I'm looking for a way to perform pointer operations in C# or .NET in particular.

我想要做的事情很简单

有IntPtr的我想要得到的IntPtr对象指向2字节领先指针。

Having a pointer IntPtr I want to get IntPtr object which points to 2 bytes ahead.

我看了一些帖子说的foolowing片段将工作...

I read some post that the foolowing snippet will work...

IntPtr ptr = new IntPtr(oldptr.ToInt32() + 2);

但我怀疑这种说法是否也适用于64位计算机(因为地址是64位有)。

But I have doubts whether this statement is also valid for 64-bit machine (since addressing is in 64-bits there)..

我发现这个优雅的方法来添加偏移量,但不幸的是,在.NET 4.0中唯一的 http://msdn.microsoft.com/en-us/library/system.intptr.add%28VS.100%29.aspx

I found this elegant method to add offset, but unfortunately is in .NET 4.0 only http://msdn.microsoft.com/en-us/library/system.intptr.add%28VS.100%29.aspx

推荐答案

我建议你使用ToInt64()和长来执行计算。这样,你会避免在64位版本的.NET框架的问题。

I suggest you to use ToInt64() and long to perform your computation. This way you will avoid problem on 64 bits version of the .NET framework.

IntPtr ptr = new IntPtr(oldptr.ToInt64() + 2);

这增添几分对32位系统的开销,但它是safier。

This add a bit of overhead on 32 bits system, but it is safier.