C# - 将不安全的 byte* 转换为 byte[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17569419/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:52:16  来源:igfitidea点击:

C# - Convert unsafe byte* to byte[]

c#pinvoke

提问by kol

I have an unsafebyte*pointing to a native byte array of known length. How can I convert it to byte[]?

我有一个unsafebyte*指向已知长度的本机字节数组。我怎样才能将它转换为byte[]

An unsafesbyte*pointing to a zero-terminated native string can be converted to a C# stringeasily, because there is a conversion constructorfor this purpose, but I can't find a simple way to convert byte*to byte[].

unsafesbyte*到零结尾的本地字符串指针可以被转换成一个C#string容易,因为有一个转换构造函数用于此目的,但我不能找到一个简单的方法来转换byte*byte[]

采纳答案by David Heffernan

If ptris your unsafe pointer, and the array has length len, you can use Marshal.Copylike this:

如果ptr是你的不安全指针,并且数组有 length len,你可以这样使用Marshal.Copy

byte[] arr = new byte[len];
Marshal.Copy((IntPtr)ptr, arr, 0, len);

But I do wonder how you came by an unsafe pointer to native memory. Do you really need unsafe here, or can you solve the problem by using IntPtrinstead of an unsafe pointer? And if so then there's probably no need for unsafe code at all.

但我确实想知道你是如何得到一个指向本机内存的不安全指针的。这里真的需要 unsafe 吗,还是可以用IntPtrunsafe 指针代替 unsafe 来解决问题?如果是这样,那么可能根本不需要不安全的代码。

回答by dotixx

The Marshalclass could help you.

元帅类可以帮助你。

byte[] bytes = new byte[length];
for(int i = 0; i < length; ++i)
  bytes[i] = Marshal.ReadByte(yourPtr, i);

I think you might use Marshal.Copy too.

我想你也可以使用 Marshal.Copy 。