I have c# method ReadBytesInTask, which is called from c++ code, using function pointer acquired with Marshal.GetFunctionPointerForDelegate method.
ReadBytesInTask gets ptr to unmanaged short[] array populates it and sends back to unmanaged code. Array is unmarshalled to unmanaged memory correctly inside method, but c++ gets only zero populated array.
What should I do?
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
private delegate int BytesReader([In,Out] IntPtr buffer, int samplesCount, string taskId);
private static readonly BytesReader _readBytesInTask = ReadBytesInTask;
private static int ReadBytesInTask(IntPtr buffer, int samplesCount)
{
var bufferSize = samplesCount;
var samplesToRead = bufferSize <= task.Buffer.Length - task.Offset ? bufferSize : task.Buffer.Length - task.Offset;
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(short))*samplesToRead);
Marshal.Copy(task.Buffer, task.Offset, buffer, samplesToRead);
task.Offset += samplesToRead;
if (samplesToRead < bufferSize) task.Offset = 0;
return samplesToRead;
}
You are changing the pointer and not what it points to. So you will need a pointer to pointer. So it would be something like this:
private static int ReadBytesInTask(IntPtr* buffer, int samplesCount)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.