關於IntPtr的資料

2021-05-01 06:19:40 字數 1499 閱讀 7525

資料一說明:

用於表示指標或控制代碼的平台特定型別。

有關此型別所有成員的列表,請參閱 intptr 成員。

system.object

system.valuetype

system.intptr

執行緒安全

此型別對多執行緒操作是安全的。

備註 intptr 型別被設計成整數,其大小適用於特定平台。即是說,此型別的例項在 32 位硬體和作業系統中將是 32 位,在 64 位硬體和作業系統上將是 64 位。

intptr 型別可以由支援指標的語言使用,並可作為在支援與不支援指標的語言間引用資料的一種通用方式。

intptr 物件也可用於保持控制代碼。例如,intptr 的例項廣泛地用在 system.io.filestream 類中來保持檔案控制代碼。

intptr 型別符合 cls,而 uintptr 型別卻不符合。只有 intptr 型別可用在公共語言執行庫中。uintptr 型別大多數是提供來維護與 intptr 型別之間的體系結構上的對稱性。

資料二說明:

c#中的intptr型別稱為「平台特定的整數型別」,它們用於本機資源,如視窗控制代碼。資源的大小取決於使用的硬體和作業系統,但其大小總是足以包含系統的指標(因此也可以包含資源的名稱)。

所以,在您呼叫的api函式中一定有類似窗體控制代碼這樣的引數,那麼當您宣告這個函式時,您應該將它顯式地宣告為intptr型別。

現在暫舉一例:

在乙個c#程式中呼叫win32api mcisendstring函式控制光碟驅動器,這個函式的函式原型是:

mcierror mcisendstring(

lpctstr lpszcommand,

lptstr lpszreturnstring,

uint cchreturn,

handle hwndcallback

); 首先在c#中宣告這個函式:

[dllimport("winmm.dll")]

private static extern long mcisendstring(string a,string b,uint c,intptr d);

然後用這樣的方法呼叫:

mcisendstring("set cdaudio door open", null, 0, this.handle);

您也可以使用intptr.zero將控制代碼設定為0;

或者使用型別強制轉換:

mcisendstring("set cdaudio door open", null, 0, (intptr)0 );

或者,使用intptr建構函式:

intptr a = new intptr(2121);

需要注意的是:

一、c#中宣告win32api時,一定要按照winapi的原型來宣告,不要改變它的資料型別;

二、盡量不要過多使用型別強制轉換或建構函式的方式初始化乙個intptr型別的變數,這樣會使程式變得難於理解並容易出錯。

以上文字僅作參考。

C 中的IntPtr型別

c 中無法將型別 int 隱式轉換為 system.intptr 這個是我引用了乙個api函式時出現的問題,我在宣告中把intptr換成了int還是不可以,這是為什麼呢?要如何處理呢?答 您好,c 中的intptr型別稱為 平台特定的整數型別 它們用於本機資源,如視窗控制代碼。資源的大小取決於使用的...

C 中的IntPtr使用

using system using system.collections.generic using system.linq using system.web using system.runtime.interopservices using system.diagnostics using s...

IntPtr和string的相互轉化

marsha有三個方法將string轉為intptr copies the contents of a managed string into unmanaged memory,converting into ansi format if required.public static intptr ...