[英]Can IntPtr be cast into a byte array without doing a Marshal.Copy?
[英]How to cast IntPtr to byte*
我正在通過interop調用一個返回out IntPtr
參數的方法。 如何獲取此IntPtr
的byte*
以便我可以對其進行操作? 我嘗試了以下方法:
fixed(byte* ptr = (byte)myIntPtr)
但它不起作用。 任何幫助,將不勝感激!
你可以簡單地寫:
byte* ptr = (byte*)int_ptr;
您不必使用fixed關鍵字。 你不想固定IntPtr,對嗎?
myIntPtr.ToPointer()
我不想在我的應用程序中使用“不安全的代碼”,所以我做了以下操作將IntPtr轉換為byte []。 給定一個名為“unsafeDataBlock”的IntPtr:
var byteArray = new byte[dataBlockSize];
System.Runtime.InteropServices.Marshal.Copy(unsafeDataBlock, byteArray, 0, dataBlockSize);
這似乎對我有用,我沒有使用Interop,但仍然在調用C Sharp的托管C ++函數。 然而,托管C ++函數稱為非托管代碼,因此它完成了與Interop相同的功能。
無論如何,在從c-sharp調用的C ++函數中,我使用了這段代碼:
(anyPointerType*) pointer = (anyPointertype*) myIntPtr.ToPointer();
如果您不想在應用程序中使用不安全的代碼,則必須使用System.Runtime.InteropServices.Marshal
的方法,或者(甚至更好)聲明您的interop函數的參數類型,以便自動進行封送處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.