我有一个C ++方法,它采用double类型的参数,例如
extern "C" {
__declspec(dllexport) void __cdecl GetResult (double resultLine);
}
在C#端,我可以调用该方法,但它总是将resultLine值转换为0.我使用DLLImport的extern功能调用C ++ DLL方法:
internal static class UnsafeNativeMethods
{
const string _dllLocation = "CoreDLL.dll";
[DllImport(_dllLocation)]
public static extern void GetResult(double resultLine);
}
我可以调用其他带字符串值的方法,一切正常但是由于某些原因,当我传递double值时它不起作用。
这是传递double值的正确方法吗?或者我需要使用ref / out等吗?
答案 0 :(得分:3)
我不是百分之百确定这是相关的,但我在这里看到的根本错误是你的调用约定错了。如果您未指定任何内容,则DllImport
属性将使用Winapi
调用约定,实际为__stdcall
,而您需要__cdecl
。
要解决此问题,请将CallingConvention
字段设置为CallingConvention.Cdecl
:
internal static class UnsafeNativeMethods
{
const string _dllLocation = "CoreDLL.dll";
[DllImport(_dllLocation), CallingConvention=CallingConvention.Cdecl]
public static extern void GetResult(double resultLine);
}
或者在C ++端将调用约定设置为__stdcall
(如果你不需要vararg __stdcall
也比__cdecl
更有效率。)
答案 1 :(得分:2)
调用约定不匹配,一方面是cdecl,另一方面是stdcall。让它们匹配,你应该重新开始营业。