我有c#方法ReadBytesInTask,它是从c ++代码调用的,使用Marshal.GetFunctionPointerForDelegate方法获取的函数指针。
ReadBytesInTask获取ptr到非托管的short []数组填充它并发送回非托管代码。在方法内正确地将数组解组为非托管内存,但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;
}
答案 0 :(得分:0)
您正在更改指针而不是指向的指针。所以你需要一个指向指针的指针。所以它会是这样的:
private static int ReadBytesInTask(IntPtr* buffer, int samplesCount)