简体   繁体   English

如何将ref字节转换为byte []?

[英]How to convert ref byte into byte[]?

Have anyone had an experience in converting ref byte into byte[] ? 有没有人有过将ref byte转换成byte[]的经验?

If the function takes an argument like 如果函数采用类似的参数

void foo(ref byte buffer);

then it is possible to call foo using 然后可以使用调用foo

void call_func()
{
    byte arr[] = new byte[10];
    foo(ref arr[0]);
}

The question is how can one re-convert the buffer argument into byte[] array in the foo . 问题是如何将buffer参数重新转换为foo中的byte[]数组。

You don't. 你没有。

In order to avoid pinning the entire array, the runtime might just make a copy of the single element you selected (and then copy back after the call). 为了避免固定整个数组,运行时可能只复制您选择的单个元素(然后在调用后复制回来)。 In that case your function will get the address of a temporary copy, which is unrelated to the address of the other array elements. 在这种情况下,您的函数将获取临时副本的地址,该副本与其他数组元素的地址无关。 (Well, there could be some aliasing considerations , this optimization is much more likely for pinvoke and/or remote calls, where aliasing analysis is more feasible) (好吧, 可能会有一些别名考虑因素 ,这种优化更可能用于pinvoke和/或远程调用,其中别名分析更可行)

If you need an array, pass the array. 如果需要数组,请传递数组。


If you don't care that it might not work right, you can use unsafe code to get to the other elements. 如果你不在乎它可能无法正常工作,你可以使用不安全的代码来获取其他元素。

pinned( byte* p = &buffer ) {
    buffer[4] = 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM