我有一个C库,这个函数返回4个输出参数调用:的P/Invoke期间编组输出指针从C#到C
void __declspec(dllexport) demofun(double a[], double b[], double* output1, double* output2, double res[], double* output3)
而且我写了一个C#包装调用的函数:
namespace cwrapper
{
public sealed class CWRAPPER
{
private CWRAPPER() {}
public static void demofun(double[] a, double[] b, double output1,
double output2, double[] res, double output3)
{ // INPUTS: double[] a, double[] b
// OUTPUTS: double[] res, double output1, double output2
// Arrays a, b and res have the same length
// Debug.Assert(a.length == b.length)
int length = a.Length;
CWRAPPERNative.demofun(a, b, length, ref output1, ref output2,
res, ref output3);
}
}
[SuppressUnmanagedCodeSecurity]
internal sealed class CWRAPPERNative
{
private CWRAPPERNative() {}
[DllImport("my_cwrapper.dll", CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, SetLastError=false)]
internal static extern void demofun([In] double[] a, [In] double[] b,
int length, ref double output1, ref double output2,
[Out] double[] res, ref double output3);
}
}
当我拨打CWRAPPERNative.demofun
方法时,一切正常。但是,当我拨打CWRAPPER.demofun
方法时,只有double[] res
正确传递。调用后输出参数output1
,output2
和output3
不变。
// ...
// Initializing arrays A and B above here
double[] res = new double[A.Length];
double output1 = 0, output2 = 0, output3 = 0;
// Works partially: output1 to 3 unchanged
CWRAPPER.demofun(A, B, output1, output2, res, output3);
// Works correctly: all outputs are changed
CWRAPPERNative.demofun(A, B, A.Length, ref output1, ref output2, res, ref output3);
我猜我是错误地编组指针参数,但我找不出修复。任何人都知道解决方案谢谢!
解决了问题!但是,与CWRAPPERNative.demofun相比,现在看来只是为了消除冗长的争论而不便。也许我应该只是通过一个结构传递输出,所以它更干净? CWRAPPER.demofun的时间比CWRAPPERNative.demofun的平均时间多出10000多次。这似乎是一个微不足道的问题,因为我们正在谈论微秒,但是要记住,我正在与C进行互动以利用AVX/SSE内在函数。你会如何优化这个?我想听听你的想法。非常感谢! – elleciel