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

标签 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 值。对于第一个,我什至准确复制了给定的代码并尝试运行它但无济于事。是什么导致了这些方法给出的错误和错误值?我怎样才能让他们工作?

为了以防万一,我自己的代码和第二篇文章的实现如下。

二分法.h

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

二分法.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)。更改一个以使它们匹配。

关于c# - 从 C# 中的 C++ 函数返回数组和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38755830/

相关文章:

c# - 如何在C#中使用Nest获取所有索引并过滤索引

c# - WPF 中的数据绑定(bind) (C#)

c++ - 为什么这个正则表达式不适用于 c++ TR1?

c++ - 如何简化我的 C++ 代码以反转字符?

c++ OpenGL 段错误

c# - ClickOnce 安装,无需开始菜单条目

c# - 为什么 Object.GetType() 是方法而不是属性?

c++ - Node.js 插件类成员函数

php - PHP 是否具有与 Python 的列表理解语法等价的功能?

c# - 为什么我在生成 Random() 数字时会得到奇怪的结果?