c# - 如何将 C# 中的二维数组传递给 C++ DLL?

标签 c# c++ arrays vector dll

我想将 C# 中的二维数组作为参数传递给 C++ DLL 中的函数(它必须是 C++,因为我使用的是 CUDA C++)。我尝试了很多东西,但未能直接使用数组或 vector 传递它。我唯一能做的就是将其转换为一维数组,将其连同其维度传递给函数,然后将其转换回二维 vector 。 这是 C++ DLL 代码:

int Add(int* a, int m, int n)
{
    int i, j, ans;
    vector<vector<int>> A(m, vector<int>(n));
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            A[i][j] = a[i * n + j];
    // Main calculations
    return ans;
}

这是传递数组的 C# 代码:

[DllImport("CUDALib.dll")]
static extern int Add(int[] a, int m, int n);
private void PassArray(int[,] A)
{
    int i, j, m, n, ans;
    int[] a;
    m = A.GetLength(0);
    n = A.GetLength(1);
    a = new int[m * n];
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            a[i * n + j] = A[i, j];
    ans = Add(a, m, n);
}

有什么更快、更有效、更直接的方法吗?

最佳答案

C# 中的二维数组是 contiguous in memory ,因此不需要在任何一侧进行所有这些内存复制。您应该按原样在 C# 中传递数组指针:

[DllImport("CUDALib.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int Add(int[,] a, int m, int n);
static void PassArray(int[,] A)
{
    int m = A.GetLength(0);
    int n = A.GetLength(1);
    int ans = Add(A, m, n);
}

然后访问 C++ 中的单个元素:

extern "C" __declspec(dllexport) int Add(int* a, int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            printf("%d %d: %d\n", i, j, a[i * n + j]);
    // Main calculations
    return 0;
}

关于c# - 如何将 C# 中的二维数组传递给 C++ DLL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59462053/

相关文章:

c++ - #ifdef 和#endif 中无法访问的代码是否在编译/链接期间被删除?

c++ - 在x86_64模式下,寄存器中无法容纳64位数字

ruby - ruby 中的并行分配对于两个等效代码片段的工作方式不同

c - 如何正确分配字符串结构数组

c# Lambda, LINQ ....改进这个方法

c++ - 在 Enter 键处拆​​分字符串

c# - 如何在 ASP.NET 中尝试 3 次无效密码后阻止用户名

c# - Newtonsoft使用类数据结构解析Json数组

c# - 在.Net MVC中进行无限循环

c# - 从 byte[] 更改图像 src