簡體   English   中英

將2D數組從C#傳遞到C ++

[英]Passing 2D array from C# to C++

我正在嘗試將浮點值的2D數組傳遞給Unity中的C ++插件。

在C ++方面,我有:

 void process_values(float** tab);

在C#端,我有一個float [,],但我不知道如何將其傳遞給我的c ++插件。

我怎樣才能做到這一點?

要將數據從CLR復制到本機代碼,請使用Marshall類。

特別

public static void Copy(
    float[] source,
    int startIndex,
    IntPtr destination,
    int length
)

在2D情況下,您必須自己計算后續行的地址。 對於每行,只需將目標浮點數乘以該行的長度即可。

public void process(float[][] input)
{
    unsafe
    {
        // If I know how many sub-arrays I have I can just fix them like this... but I need to handle n-many arrays
        fixed (float* inp0 = input[0], inp1 = input[1] )
        {
            // Create the pointer array and put the pointers to input[0] and input[1] into it
            float*[] inputArray = new float*[2];
            inputArray[0] = inp0;
            inputArray[1] = inp1;
            fixed(float** inputPtr = inputArray)
            {
                // C function signature is someFuction(float** input, int numberOfChannels, int length)
                functionDelegate(inputPtr, 2, input[0].length);
            }
        }
    }
}

示例C#:

[DllImport("Win32Project1.dll", EntryPoint = "?Save@@YAXPAPAM@Z", CallingConvention = CallingConvention.Cdecl)]
        static extern void Save(IntPtr arr);
static void Main(string[] args)
        {

            float[][] testA = new float[][] { new float[] { 1.0f, 2.0f }, new float[] { 3.0f, 4.0f } };

                IntPtr initArray = Marshal.AllocHGlobal(8);
                IntPtr arrayAlloc = Marshal.AllocHGlobal(sizeof(float)*4);

                Marshal.WriteInt32(initArray, arrayAlloc.ToInt32());
                Marshal.WriteInt32(initArray+4, arrayAlloc.ToInt32() + 2 * sizeof(float));
                Marshal.Copy(testA[0], 0, arrayAlloc, 2);
                Marshal.Copy(testA[1], 0, arrayAlloc + 2*sizeof(float), 2);

                Save(initArray); // C func call

                Marshal.FreeHGlobal(arrayAlloc);
                Marshal.FreeHGlobal(initArray);

                Console.ReadLine();

        }

暫無
暫無

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

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