从 C# 中的 C++ 函数返回数组和结构

returning arrays and structs from a c++ function in c#

我有一个用 c++ 编写的函数,我将其放入 dll 中并使用 DllImport 在 c# 中使用。一切正常;我能够从 C++ 中获取 return 值并将其显示在我的 C# GUI 中。现在我想添加到那个函数并让它 return 多个值(到目前为止 3 个)。我试过 Return C++ array to C# and How to return two different variable in c++? 中给出的方法,但都不起作用。 第一个 post 的代码给了我一个访问冲突错误,第二个代码给了我结构的所有 0 值。对于第一个,我什至准确地复制了给定的代码并尝试 运行 它但无济于事。是什么导致了这些方法给出的错误和错误值?我怎样才能让他们工作?

为了以防万一,下面是我自己的代码以及第二个 post 的实现。

bisection.h

 struct Result
{
    double root;
    double relError;
    double absError;
}result;
extern "C" {__declspec(dllexport) Result bisection( double l, double u, double stoppingError, int maxIter); }

bisection.cpp

Result bisection(double l, double u, double stoppingError, int maxIter) {
//code for this function
result.root = xr;
result.relError = e;
result.absError = 1;    
return result;
}

c#代码

    [StructLayout(LayoutKind.Sequential)]
    public struct Result
    {
        public double root;
        public double relError;
        public double absError;            
    }
    [DllImport(dllPath)]
    private static extern Result bisection(double l, double u, double stoppingError, int maxIter);

Result result = bisection(data[0], data[1], 0.1, 100);

您的代码几乎是正确的。调用约定不匹配。 C++ 代码使用 cdecl,即 C# stdcall。换一个,使它们匹配。