我有一个用c++编写的函数,我把它放在一个dll中,并使用DllImport在c#中使用它。一切正常;我能够从c++获取返回值,并将其显示在我的c#图形用户界面中。现在我想添加到该函数中,并让它返回多个值(到目前为止有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#代码
[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);发布于 2016-08-04 13:07:00
您的代码几乎是正确的。调用约定不匹配。C++代码使用C#标准调用cdecl。更改一个,使它们匹配。
https://stackoverflow.com/questions/38755830
复制相似问题