我有一个 C# 应用程序,我在其中创建了一个 3D Int16(short) 数组。想要将此 3D 数组传递给 C++ 库,以将此数据设置为 1D 字节数组形式的对象。因此,方案要么在将数据传递给库之前对其进行转换,要么在库本身中进行转换。
- 我知道如何在 C# 中将 3D Int16 数组转换为 1D 字节数组,但我不知道如何使用 C++ 将其转换?
- 关于我在 C# 中使用
ConvertAll
,C++ 或 C# 哪个更快? - 内存是否会加倍,或者我可以将 C++ 库中对象的数据设置为指向我在 C# 中拥有的同一卷?
最佳答案
I know how to convert the 3D Int16 array to 1D byte array in C# but I don't know how to convert it using C++?
这取决于您希望一维数组中的行、列和深度如何排列。我没有看到任何转换它的理由,因为您可以按照您想要的方式随机访问元素。当您不需要时,没有理由承担此类操作的费用。如果您不将其存储在文件中或通过网络发送它,我不明白您为什么要序列化它。
为什么你不能这样做:
__declspec( dllexport ) void cppMatrixCode(__int16*** matrix_3d, int width, int height, int depth)
{
//manipulate the matrix with matrix_3d[the row you want][col you want][depth you want]
//or to serialize:
for(int i = 0; i < width; i++)
for(int j = 0; j < height; j++)
for(int k = 0; k < depth; k++)
{
_int16 value = matrix_3d[i][j][k];
//now add value to another array or whatever you want.
}
}
in C#
[DllImport("YourDLLGoesHere")]
static extern void cppMatrixCode(short[,,] matrix_3d, int width, int height, int depth);
short[,,] matrix = new short[width, height, depth];
//add your values to matrix
cppMatrixCode(matrix, width, height, depth);
这应该只在 32 位系统上复制 128 个字节,或在 64 位系统上复制 160 个字节。
Which one will be faster C++ or C#, regarding that I use ConvertAll in C#?
这取决于您具体在做什么,但是编写良好的 C++ 代码通常比 CLI 代码更快。
Will the memory be doubled or I can just set the data of the object in the C++ library to point to the same volume I have in C#?
您应该能够通过引用将 C# byte[] 传递给 c++ 函数,而无需复制任何数据。不过,我们需要更多详细信息来了解您到底想做什么。
关于c# - 将 C# 3D 数组作为 1D 字节数组传递给 C++ 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783586/