0

我有 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;
}
4

1 回答 1

0

您正在更改指针,而不是它指向的内容。所以你需要一个指向指针的指针。所以它会是这样的:

private static int ReadBytesInTask(IntPtr* buffer, int samplesCount)
于 2012-11-02T13:40:06.503 回答