我有 c# 方法 ReadBytesInTask,它是从 c++ 代码调用的,使用通过 Marshal.GetFunctionPointerForDelegate 方法获取的函数指针。
ReadBytesInTask 获取指向非托管 short[] 数组的 ptr 填充它并发送回非托管代码。数组在方法内部被正确解组为非托管内存,但 c++ 仅获得零填充数组。
我应该怎么办?
[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;
}