C#中的byte []到byte*

Ser*_*gey 6 c# multilingual types primitive-types

我创建了2个程序 - 在C#和C++中,都从C dll 调用本机方法.C++工作正常,因为有相同的数据类型,C#不起作用.

而原生函数参数是unsigned char*.我byte[]在C#中试过,它没用,然后我尝试了:

fixed(byte* ptr = byte_array) {
  native_function(ptr, (uint)byte_array.Length);
}
Run Code Online (Sandbox Code Playgroud)

它也行不通.以byte*这种方式转换字节数组是否正确?它是正确的在C#中使用字节作为unsigned charÇ

编辑:这东西返回错误的结果:

byte[] byte_array = Encoding.UTF8.GetBytes(source_string);
nativeMethod(byte_array, (uint)byte_array.Length);
Run Code Online (Sandbox Code Playgroud)

这个东西也会返回错误的结果:

 byte* ptr;
 ptr = (byte*)Marshal.AllocHGlobal((int)byte_array.Length);
 Marshal.Copy(byte_array, 0, (IntPtr)ptr, byte_array.Length);
Run Code Online (Sandbox Code Playgroud)

MrF*_*Fox 6

unsafe class Test
{
    public byte* PointerData(byte* data, int length)
    {
        byte[] safe = new byte[length];
        for (int i = 0; i < length; i++)
            safe[i] = data[i];

        fixed (byte* converted = safe)
        {
            // This will update the safe and converted arrays.
            for (int i = 0; i < length; i++)
                converted[i]++;

            return converted;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还需要在构建属性中设置"使用不安全代码"复选框.


use*_*016 2

你必须整理byte[]

[DllImport("YourNativeDLL.dll")]
public static extern void native_function
(
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
    byte[] data,
    int count // Recommended
);
Run Code Online (Sandbox Code Playgroud)