gpt4 book ai didi

c# - 从 C# 到 C++ 的数组再返回,没有不安全的代码

转载 作者:行者123 更新时间:2023-11-30 01:38:11 24 4
gpt4 key购买 nike

<分区>

我知道这个问题已经被问过并且可能被认为是重复的,但是在阅读了其他答案之后我仍然很困惑并且不理解那里提供的解释。

如果有人能提供示例代码 一些解释,我将不胜感激。

我正在处理以下任务:
我在 Unity 中有一个纹理/纹理(无法从驱动器加载,动态生成)并将其转换为数组。它可以是 int、byte 或 float 的数组。

目前,我在 C# 中进行对象检测,但我想让它更快。因此,我想做以下事情。
访问 C++ 代码(从 dll,我刚刚开始我的 C++ 之旅)并运行一个方法,该方法将获取我的输入数组,进行计算并将新数组(旧数组未修改)返回给 C# 代码。

或者,我可以输入两个数组(首选),其中一个被修改。
输出数组不必每次都创建,可以覆盖。我不能在 C# 中使用不安全的代码,因为这是出于 Assets 目的(兼容性问题)。

模型代码

C#
create arrays aOne,aTwo;
SomeC++Method(aOne,ref aTwo)
or
aTwo = SomeC++Method(aOne,aTwo)
or
aTwo = SomeC++Method(aOne) // variant where aTwo is created in C++

SomeC++MethodToDeAllocateMemory() //so there is no memory leak

C++
SomeC++Method(aOne,aTwo)
for (xyz)
do someting
return modified aTwo
SomeC++MethodToDeAllocateMemory()
release memory

我在这里找到了这个问题的答案: Updating a C# array inside C++ without Marshal.Copy or Unsafe

示例解决方案:

C++代码:

extern "C" __declspec(dllexport) bool PopulateArray(float* floats, int length)
{
for (int i = 0; i < length; ++i)
{
floats[i] = i;
}

return true;
}

C#代码

using UnityEngine;
using System.Runtime.InteropServices;

public class Test : MonoBehaviour {

[DllImport("ArrayFilling", CallingConvention = CallingConvention.Cdecl)]
public static extern bool PopulateArray([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] float[] floats, int length);

int length = 4000000; //corresponds to 2000x2000 texture of grayscale values

void Start()
{
//create new array
float[] floats = new float[length];

//used for speed test
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

//check internal method speed
sw.Start();
//floats array gets update here
Populate(ref floats);
sw.Stop();
Debug.Log("internal: " + sw.ElapsedMilliseconds);
sw.Reset();

//check external method speed
sw.Start();
//floats array gets updated here
PopulateArray(floats, length);
sw.Stop();
Debug.Log("external: " +sw.ElapsedMilliseconds);

}

void Populate(ref float[] floats)
{
for (int i = 0,n = length; i<n;i++)
{
floats[i] = i;
}
}
}

关于速度:
-外部方法 (DLL) - 5 毫秒
-内部方法(无效填充)- 23 毫秒

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com