【问题标题】:How can I pass in a pointer to a pointer of a UInt16 array to a Marshalled function?如何将指向 UInt16 数组指针的指针传递给编组函数?
【发布时间】:2013-07-19 12:54:32
【问题描述】:

我正在尝试将一个指向 UInt16 数组指针的指针发送到一个编组函数,就像在 C# 中这样:

C++:

int foo(Unsigned_16_Type** Buffer_Pointer);

C#:

[DllImport("example.dll")]
public static extern int foo(IntPtr Buffer_Pointer);

UInt16[] bufferArray = new UInt16[32];

IntPtr p_Buffer = (IntPtr)Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(UInt16)) * bufferArray.Length);
Marshal.Copy(bufferArray, 0, p_Buffer, bufferArray.Length);  //Issue is here

GCHandle handle = GCHandle.Alloc(p_Buffer, GCHandleType.Pinned);
IntPtr ppUnmanagedBuffer = (IntPtr)handle.AddrOfPinnedObject();

UInt16 word_count = 0;

this.lstbox_DATA_WORDS.Items.Clear();

if ( foo(ppUnmanagedBuffer );

我的主要问题是Marshal.Copy,对于作为源数组的第一个参数,它不需要UInt16[]。我想知道是否有人知道如何将Marshal.CopyUInt16 数组一起使用。

【问题讨论】:

    标签: c# arrays pointers marshalling uint16


    【解决方案1】:

    没有采用无符号短数组的Marshal.Copy 重载。幸运的是,ushortshort 的大小相同,因此您可以使用 Marshal.Copy(Int16[], IntPtr, int) 重载。您只需先将您的ushort[] 强制转换为short[]

    可能最快的方法是使用Buffer.BlockCopy。它复制字节,所以你只需要告诉它每个条目复制 2 个字节:

    short[] temp = new short[bufferArray.Length];
    System.Buffer.BlockCopy(bufferArray, 0, temp, 0, temp.Length * 2);
    

    这会将无符号的 16 位整数值复制到有符号的 16 位整数数组中,但底层字节值将保持不变,非托管代码不会知道其中的区别。

    【讨论】:

    • System.Buffer.BlockCopy(bufferArray, 0, temp, 0, temp.Length * 2]; 最后应该有一个 ) 不是 ],否则效果很好,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-08-08
    • 2017-08-09
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多