简体   繁体   English

在没有Marshal.Copy或Unsafe的情况下在C ++中更新C#数组

[英]Updating a C# array inside C++ without Marshal.Copy or Unsafe

I am wanting to update an array that was created inside C#, and then pass a pointer to that array over to C++ and let C++ populate the indexes, to be used back in C#. 我想更新在C#中创建的数组,然后将指向该数组的指针传递给C ++,然后让C ++填充索引,以供在C#中使用。 Right now I am Using a Marshal.Copy() to accomplish this task, but I would like to avoid the potentially unnecessary copy, and call back to c++ to release the array. 现在,我正在使用Marshal.Copy()完成此任务,但我想避免可能不必要的复制,并返回c ++释放数组。 Is this even possible? 这有可能吗?

These array are floats and ints, for geometric mesh data. 这些数组是浮点数和整数,用于几何网格数据。

My current usage (working and not what I want to use) C# 我当前的用法(正在工作,而不是我想使用的)C#

    IntPtr intptr=new IntPtr();
    int count = 0;
    PopulateArray(ref intptr, ref count);
    float[] resultVertices = new float[count];
    Marshal.Copy(intptr, resultVertices, 0, count);

C++ C ++

extern "C" __declspec(dllexport) bool PopulateArray(float** resultVerts, int* resultVertLength){

    *resultVerts = new float[5]{0.123f, 3.141529f, 127.001f, 42.42f, 0};
    int myX = 5;
    *resultVertLength = myX;
    return true;
}

The only safe way to have C++ code update a managed C# array is to pin the array. 使C ++代码更新托管C#数组的唯一安全方法是固定该数组。 Otherwise, it's possible for the garbage collector to try to move the array while the native code is running. 否则,垃圾收集器有可能在本机代码运行时尝试移动数组。 You can do this with a GCHandle object. 您可以使用GCHandle对象执行此操作。

int count = 5; 
float[] resultVertices = new float[count];

GCHandle handle = GCHandle.Alloc(resultVertices, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();

PopulateArray(address, count);

handle.Free();

It can also be done with unsafe code, which is somewhat more intuitive to read and remember: 也可以使用不安全的代码来完成,这样阅读和记忆起来会更直观:

int count = 5; 
float[] resultVertices = new float[count];
unsafe 
{
    fixed(float* ptr = resultVertices)
    {
        PopulateArray(ptr, count);
    }
}

Another alternative is to have C# allocate an unmanaged chunk of memory and pass that to the C++ method. 另一种选择是让C#分配一个非托管内存块并将其传递给C ++方法。 This is better than what you're doing because you are not placing the responsibility of allocation/deallocation in the C++ library code and instead keeping that all in your C#. 这比您所做的要好,因为您没有将分配/取消分配的责任放在C ++库代码中,而是将所有这些都保留在C#中。 I know you want to avoid the coy but sometimes doing the copy is more performant than pinning objects, but it depends on how large they are. 我知道您想避免遇到麻烦,但是有时复制比固定对象更有效,但这取决于它们的大小。 I recommend you do performance testing to determine which is best for your situation. 我建议您进行性能测试以确定最适合您的情况。

int count = 5; 
float[] resultVertices = new float[count];
IntPtr unmanagedMemory = Marshal.AllocHGlobal(count * Marshal.SizeOf(typeof(float)));
PopulateArray(unmanagedMemory, count);
Marshal.Copy(unmanagedMemory, resultVertices, 0, count);

In all these scenarios you should set your C++ code to operate like this: 在所有这些情况下,您都应该将C ++代码设置为如下所示:

extern "C" __declspec(dllexport) bool PopulateArray(float* resultVerts, int vertLength)
{
    resultVerts[0] = 0.123f;
    // fill out the rest of them any way you like.
    return true;
}

If the array size is variable, then I recommend having a separate C++ method that calculates the size and returns it rather than having the C++ method allocate the memory. 如果数组大小是可变的,那么我建议使用单独的C ++方法来计算大小并返回大小,而不是让C ++方法分配内存。

If you are willing to allow C# to allocate the array (probably a safer alternative) then you could do this behavior with standard PInvoke attributes. 如果您愿意允许C#分配数组(可能是一个更安全的选择),则可以使用标准PInvoke属性来执行此行为。

Change your C++ declaration to: 将您的C ++声明更改为:

extern "C" __declspec(dllexport) bool PopulateArray(float resultVerts[], int resultVertLength)

and your C# declaration to: 和您的C#声明:

[DllImport("Win32Library.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool PopulateArray([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] float[] resultVerts, int resultVertLength);

Your usage from the C# side would then change to: 然后,您在C#方面的用法将更改为:

var resultVertices = new float[5];
PopulateArray(resultVertices, resultVertices.Length);

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

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