Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c# - Add offset to IntPtr

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

I want to do something very simple

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

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

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

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

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

question from:https://stackoverflow.com/questions/1866236/add-offset-to-intptr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...