简体   繁体   English

将带有数组的IntPtr返回到C ++

[英]Return IntPtr with array to c++

I have c# method ReadBytesInTask, which is called from c++ code, using function pointer acquired with Marshal.GetFunctionPointerForDelegate method. 我有c#方法ReadBytesInTask,它使用通过Marshal.GetFunctionPointerForDelegate方法获取的函数指针从c ++代码中调用。

ReadBytesInTask gets ptr to unmanaged short[] array populates it and sends back to unmanaged code. ReadBytesInTask将ptr放入非托管short []数组中,然后将其发送回非托管代码。 Array is unmarshalled to unmanaged memory correctly inside method, but c++ gets only zero populated array. 数组未在方法内部正确编组为非托管内存,但C ++仅获得零填充数组。
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM