[英]C# how to get an array of int* from unmanaged C++
在非托管端,我有short* m_pLevels[4]
,我需要獲取指向 C# 端的指針數組,以便我可以使用每個點從非托管端復制到托管數組。
如何獲得一個short*
到 C# 的數組,該數組是IntPtr
的數組嗎?
我建議使用C++/CLI在 C#(托管)和 C++(本機)之間進行通信。 在下面的示例中,我使用了最簡單的情況,即本機數據只是 1 個二進制緩沖區。 您可以對其進行調整以傳遞任何形式的本機數據。
您可以采用以下兩種方法之一:
最有效的是將非托管數據傳遞給 C# 並按原樣使用。 您將不得不使用unsafe
的方法來處理原始指針。 這很有效,但風險更大。 獲取本機緩沖區的不安全 C# 方法的示例:
unsafe void HandleNativeData(sbyte* pData, int dataLen) { ... }
最安全的方法是將非托管內存編組為托管內存。 例如,如果您有一個從 C++ 獲得原始指針的 C# 或 C++/CLI 方法(如方法 1),您可以執行以下操作:
unsafe void HandleNativeData(sbyte* pData, int dataLen) { byte[] DataManagedBuf = new byte[dataLen]; Marshal.Copy((IntPtr)pData, DataManagedBuf, 0, dataLen); // At this point DataManagedBuf is a proper managed buffer, // containing the data that was passed from native C++. }
PInvoke 也是一個選項:
// this function pre-supposes that everyone knows there are always
// exactly 4 buffers of data. that's pretty rare for IRL interop.
// normally you'd use a struct with fixed length arrays, but the
// question explicitly states short*[].
[DllImport("UnmanagedCode.dll", EntryPoint = "NameOfUnmanagedCodeFunction"]
private static extern void GetUnmanagedBuffers(IntPtr[] shortPtrs, int[] lengths);
// this function will call the unmanaged function and then
// marshal over the pointers into managed arrays
public List<short[]> GetBuffers()
{
var managedArrays = new List<short[]>(4);
// the unmanaged DLL fills in the buffer addresses for us
var shortPtrs = new IntPtr[4];
// and the lengths of each buffer
var lengths = new int[4];
GetUnmanagedBuffers(shortPtrs, lengths);
// input validation/exception handling omitted for brevity
for (int i = 0; i < 4; i++)
{
var length = bufferLengths[i];
// create the array and add it to the return values
managedArrays.Add(new short[length]);
// the overload of Marshal.Copy that works with int16[]
Marshal.Copy(bufferPtrs[i], //source pointer
managedArrays[i], //destination array
0, //starting index into dest
length) //number of int16 to copy
}
// often you'd see another PInvoke here telling the unmanaged
// code that you're done with the buffers so they can be freed.
return managedArrays;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.