當前位置: 首頁>>代碼示例>>C#>>正文


C# IntPtr結構體代碼示例

本文整理匯總了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);
    }
}
開發者ID:.NET開發者,項目名稱:System,代碼行數:44,代碼來源:IntPtr

輸出:

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);
    }
}
開發者ID:C#程序員,項目名稱:System,代碼行數:21,代碼來源:IntPtr


注:本文中的System.IntPtr結構體示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。