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

时间:2016-08-04 00:47:54

标签: c# c++ arrays struct dllimport

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

以防万一需要,我自己的代码与第二篇文章的实现如下。

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#c​​ode

    [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);

1 个答案:

答案 0 :(得分:2)

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