简体   繁体   English

如何使用DLLImport将双精度值传递给C ++参数?

[英]how do i pass a double value to a C++ parameter using DLLImport?

I have a C++ method and it takes a parameter of type double eg 我有一个C ++方法,它需要一个double类型的参数,例如

extern "C" {
    __declspec(dllexport) void __cdecl GetResult (double resultLine);
}

On the C# side, I can call the method but it always converts the resultLine value to 0. I am calling the C++ DLL method using DLLImport's extern feature: 在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);
}

I can call the other methods that take the string value and everything works but for some reason, it doesn't work when I pass the double value. 我可以调用采用字符串值的其他方法,并且一切正常,但是由于某种原因,当我传递双精度值时它不起作用。

Is that the correct way to pass the double value? 那是传递双精度值的正确方法吗? or do I need to use ref/out etc? 还是我需要使用ref / out等?

I'm not 100% sure this is related, but the fundamental mistake I see here is that you got the calling convention wrong. 我不是100%确信这是相关的,但是我在这里看到的根本错误是调用约定错误。 If you don't specify anything, the DllImport attribute will use the Winapi calling convention, which is actually __stdcall , while you need __cdecl . 如果您未指定任何内容,则DllImport属性将使用Winapi调用约定,该约定实际上是__stdcall ,而您需要__cdecl

To fix this problem set the CallingConvention field to CallingConvention.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);
}

or set the calling convention to __stdcall on the C++ side (if you don't need vararg __stdcall is also a bit more efficient than __cdecl ). 或者在C ++端将调用约定设置为__stdcall (如果不需要vararg,则__stdcall__cdecl效率更高)。

You have a mismatch of calling conventions, cdecl on one side and stdcall on the other. 您的调用约定不匹配,一方面是cdecl,另一方面是stdcall。 Make them match and you should be back in business. 使它们匹配,您应该重新营业。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM