如何将指向UInt16数组的指针的指针传递给Marshalled函数? [英] How can I pass in a pointer to a pointer of a UInt16 array to a Marshalled function?

查看:106
本文介绍了如何将指向UInt16数组的指针的指针传递给Marshalled函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将指向UInt16数组的指针的指针发送给编组函数,如C#中这样:

I'm attempting to send a pointer to a pointer of a UInt16 array to a marshalled function like so in 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数组一起使用.

My main problem is with the Marshal.Copy, for the first argument which is the source array, it does not take a UInt16[]. I was wondering if anyone knew how to use Marshal.Copy with a UInt16 array.

推荐答案

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

There is no Marshal.Copy overload that takes an unsigned short array. Fortunately, ushort and short are the same size, so you can use the Marshal.Copy(Int16[], IntPtr, int) overload. You just need to coerce your ushort[] into a short[] first.

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

Probably the fastest way to do this is to use Buffer.BlockCopy. It copies bytes, so you just have to tell it to copy 2 bytes per entry:

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

这会将无符号的16位整数值复制到一个有符号的16位整数数组中,但是基础字节值将保持不变,并且非托管代码将不知道它们之间的区别.

This will copy the unsigned 16-bit integer values into a signed 16-bit integer array, but the underlying byte values will remain the same, and the unmanaged code won't know the difference.

这篇关于如何将指向UInt16数组的指针的指针传递给Marshalled函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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