c# - How can I pass in a pointer to a pointer of a UInt16 array to a Marshalled function? -


i'm attempting send pointer pointer of uint16 array marshalled function 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 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 ); 

my main problem marshal.copy, first argument source array, not take uint16[]. wondering if knew how use marshal.copy uint16 array.

there no marshal.copy overload takes unsigned short array. fortunately, ushort , short same size, can use marshal.copy(int16[], intptr, int) overload. need coerce ushort[] short[] first.

probably fastest way use buffer.blockcopy. copies bytes, have tell copy 2 bytes per entry:

short[] temp = new short[bufferarray.length]; system.buffer.blockcopy(bufferarray, 0, temp, 0, temp.length * 2); 

this copy unsigned 16-bit integer values signed 16-bit integer array, underlying byte values remain same, , unmanaged code won't know difference.


Comments