簡體   English   中英

將帶有數組的IntPtr返回到C ++

[英]Return IntPtr with array to c++

我有c#方法ReadBytesInTask,它使用通過Marshal.GetFunctionPointerForDelegate方法獲取的函數指針從c ++代碼中調用。

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;
}

您正在更改指針,而不是它指向的指針。 因此,您將需要一個指向指針的指針。 所以會是這樣的:

private static int ReadBytesInTask(IntPtr* buffer, int samplesCount)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM