C# 如何将 IntPtr 转换为字节 *
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/713324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast IntPtr to byte*
提问by Dmitri Nesteruk
I'm calling a method via interop that returns an out IntPtr
parameter. How can I get a byte*
for this IntPtr
so I can operate on it? I tried the following:
我正在通过返回out IntPtr
参数的互操作调用方法。我怎样才能byte*
为此获得一个,IntPtr
以便我可以对其进行操作?我尝试了以下方法:
fixed(byte* ptr = (byte)myIntPtr)
but it didn't work. Any help would be appreciated!
但它没有用。任何帮助,将不胜感激!
采纳答案by Jb Evain
You can simply write:
你可以简单地写:
byte* ptr = (byte*)int_ptr;
You don't have to use the fixedkeyword. You don't want to pin the IntPtr, do you?
您不必使用fixed关键字。你不想固定 IntPtr,是吗?
回答by Noldorin
myIntPtr.ToPointer()
myIntPtr.ToPointer()
回答by Anton Tykhyy
If you don't want unsafe code in your application, you'll have to use the methods in System.Runtime.InteropServices.Marshal
, or (even better) declare your interop functions' parameter types so the marshaling happens automatically.
如果您不想在应用程序中使用不安全的代码,则必须使用 中的方法System.Runtime.InteropServices.Marshal
,或者(甚至更好)声明互操作函数的参数类型,以便自动进行封送处理。
回答by Dimitri C.
I didn't want "unsafe code" in my application, so I did the following to convert an IntPtr to a byte[]. Given an IntPtr called "unsafeDataBlock":
我不想在我的应用程序中使用“不安全代码”,因此我执行了以下操作将 IntPtr 转换为 byte[]。给定一个名为“unsafeDataBlock”的 IntPtr:
var byteArray = new byte[dataBlockSize];
System.Runtime.InteropServices.Marshal.Copy(unsafeDataBlock, byteArray, 0, dataBlockSize);
回答by JD.
This seemed to work for me, I wasn't using Interop but was still calling a managed C++ function from C Sharp. The managed C++ function however called unmanaged code so it accomplished the same thing as Interop.
这似乎对我有用,我没有使用 Interop,但仍在从 C Sharp 调用托管 C++ 函数。然而,托管 C++ 函数调用非托管代码,因此它完成了与 Interop 相同的事情。
Anyway, in the C++ function that was called from c-sharp, I used this code:
无论如何,在从 c-sharp 调用的 C++ 函数中,我使用了以下代码:
(anyPointerType*) pointer = (anyPointertype*) myIntPtr.ToPointer();