我试图将一个浮点数值的二维数组传递给Unity中的C++插件。从C#传递二维数组到C++
在C++方面我有:
void process_values(float** tab);
在C#身边,我已经有了一个浮[,]我不知道如何将它传递给我的C++插件。
我该怎么做?
我试图将一个浮点数值的二维数组传递给Unity中的C++插件。从C#传递二维数组到C++
在C++方面我有:
void process_values(float** tab);
在C#身边,我已经有了一个浮[,]我不知道如何将它传递给我的C++插件。
我该怎么做?
将数据从CLR复制到本地代码使用Marshall类。
具体
public static void Copy(
float[] source,
int startIndex,
IntPtr destination,
int length
)
在2D情况下,你必须计算自己后续行的地址。 对于每一行,只需添加到float time lenght行的目标指针大小即可。
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 = "[email protected]@[email protected]", 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();
}
那么,我最终得到的变量的国王,IntPtr的数组? – kakou
intptr只是您要复制数据的内存地址。在我的选择中,你将不得不为C++中的浮点数组分配内存。然后你可以用元帅复制数据。 – stepandohnal
或者,您可以使用不安全的代码。 fixed(float ** inputPtr = inputArray) {C} functionn(float **) function(inputPtr); } – stepandohnal
它是否必须是一个二维数组?或者你可以将它内联为一个单一的数组(即每一行都遵循先前的内存)?传递一个数组会更容易。 –
如果不能修改C++插件...它已经被其他人完成 – kakou
它将如何知道2d数组的列大小? –