本文整理汇总了C#中System.IntPtr结构体的典型用法代码示例。如果您正苦于以下问题:C# IntPtr结构体的具体用法?C# IntPtr怎么用?C# IntPtr使用的例子?那么恭喜您, 这里精选的结构体代码示例或许可以为您提供帮助。
IntPtr结构体属于System命名空间,在下文中一共展示了IntPtr结构体的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Runtime.InteropServices;
class NotTooSafeStringReverse
{
static public void Main()
{
string stringA = "I seem to be turned around!";
int copylen = stringA.Length;
// Allocate HGlobal memory for source and destination strings
IntPtr sptr = Marshal.StringToHGlobalAnsi(stringA);
IntPtr dptr = Marshal.AllocHGlobal(copylen + 1);
// The unsafe section where byte pointers are used.
unsafe
{
byte *src = (byte *)sptr.ToPointer();
byte *dst = (byte *)dptr.ToPointer();
if (copylen > 0)
{
// set the source pointer to the end of the string
// to do a reverse copy.
src += copylen - 1;
while (copylen-- > 0)
{
*dst++ = *src--;
}
*dst = 0;
}
}
string stringB = Marshal.PtrToStringAnsi(dptr);
Console.WriteLine("Original:\n{0}\n", stringA);
Console.WriteLine("Reversed:\n{0}", stringB);
// Free HGlobal memory
Marshal.FreeHGlobal(dptr);
Marshal.FreeHGlobal(sptr);
}
}
输出:
Original: I seem to be turned around! Reversed: !dnuora denrut eb ot mees I
示例2: new IntPtr
//引入命名空间
using System;
using System.IO;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public class MainClass
{
public unsafe static void Main()
{
int a = 10;
Console.WriteLine("a is {0} ({0:X})", a);
IntPtr ip = new IntPtr(&a);
byte* pTarget = (byte*)ip.ToPointer() + 1;
*pTarget = 2;
Console.WriteLine("a is {0} ({0:X})", a);
}
}