首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c#中从c++函数返回数组和结构

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

Stack Overflow用户
提问于 2016-08-04 08:47:54
回答 1查看 209关注 0票数 2

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

如果需要的话,下面是我自己的代码和第二篇文章的实现。

bisection.h

代码语言:javascript
复制
 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

代码语言:javascript
复制
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#代码

代码语言:javascript
复制
    [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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-04 13:07:00

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38755830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档