如何正确地将浮点数从c#传递到c++ (dll)

How to correctly pass a float from C# to C++ (dll)

本文关键字:c++ dll 正确地 浮点数      更新时间:2023-10-16

当我从c#传递浮点数到c++时,我得到了巨大的差异。我传递的是一个随时间变化的动态浮动。使用调试器,我得到以下内容:

c++ lonVel    -0.036019072    float
c#  lonVel    -0.029392920    float

我确实将我的msvc++ 2010浮点模型设置为/fp:fast,如果我没弄错的话,这应该是。net中的标准,但这没有帮助。

现在我不能给出代码,但我可以展示一小部分。

从c#的角度来看是这样的:

namespace Example
{
    public class Wheel
    {       
        public bool loging = true;
        #region Members     
        public IntPtr nativeWheelObject; 
        #endregion Members
        public Wheel()
        {           
            this.nativeWheelObject = Sim.Dll_Wheel_Add();
            return;
        }
        #region Wrapper methods 
        public void SetVelocity(float lonRoadVelocity,float latRoadVelocity {
              Sim.Dll_Wheel_SetVelocity(this.nativeWheelObject, lonRoadVelocity, latRoadVelocity);
        }
        #endregion Wrapper methods
    }
    internal class Sim
    {
        #region PInvokes
        [DllImport(pluginName, CallingConvention=CallingConvention.Cdecl)]
                public static extern void Dll_Wheel_SetVelocity(IntPtr wheel,
                     float lonRoadVelocity, float latRoadVelocity);
        #endregion PInvokes 
    }       
}

在c++端@ exportFunctions.cpp:

EXPORT_API void Dll_Wheel_SetVelocity(CarWheel* wheel, float lonRoadVelocity,
     float latRoadVelocity) {
        wheel->SetVelocity(lonRoadVelocity,latRoadVelocity);
}

有什么建议,我应该做什么,以获得1:1的结果或至少99%的正确结果

我相信这可能描述了你的问题,http://msdn.microsoft.com/en-us/library/c151dt3s.aspx

如果可能的话,我建议选择另一种数据类型。

float可以从一个程序更改到另一个程序,甚至可以在同一个应用程序中更改。下面是一些关于这个主题的阅读:http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

因此,您可以实现"AlmostEqual"方法,或者简单地选择另一种数据类型。

仍然没有找到一种方法来完全解决我的问题,但对于其他人可能有同样的问题,设置/fp:fast和/arch:SSE2让我更接近!

出现问题的地方的调试结果:

latRoadVelocity -0.15862428 float
lonRoadVelocity -0.036250707    float
wheel->latRoadVelocity  -0.15102120 float
wheel->lonRoadVelocity  -0.036250707    float

你可以看到我的lonRoadVelocity目前是1:1,但仍然有一些小的差异在latRoadVelocity。我看看能不能把这个也做成1:1