C# - 转换不安全字节*为byte [] [英] C# - Convert unsafe byte* to byte[]

查看:156
本文介绍了C# - 转换不安全字节*为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不安全 字节* 指向已知长度的本地字节数组。我怎样才能将其转换为字节[]

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

这是不安全 为sbyte * 指着一个零封端的本地字符串可以转换为C#字符串容易,因为有一个的为此转换构造,但我无法找到一个简单的方法来转换字节* 字节[ ]

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

推荐答案

如果 PTR 是您不安全的指针,数组长度为 LEN ,您可以使用 Marshal.Copy 是这样的:

If ptr is your unsafe pointer, and the array has length len, you can use Marshal.Copy like this:

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



不过,我想知道你是怎么来通过一个不安全的指针指向本机内存。你是否真的需要这里不安全,或者您可以通过使用解决的IntPtr ,而不是一个不安全的指针问题?如果是的话那么可能不需要不安全的代码在所有。

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 IntPtr instead of an unsafe pointer? And if so then there's probably no need for unsafe code at all.

这篇关于C# - 转换不安全字节*为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆