如何正确地将浮点数从c#传递到c++ (dll)
How to correctly pass a float from C# to C++ (dll)
当我从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
相关文章:
- 挂起和取消挂起一个文件DLL
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 导入库可以跨dll版本工作吗
- 从C++dll访问C#中的一行主要参数
- 链接到自行创建的dll失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- C++:将外部库链接到dll库
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 不同的Visual Studio版本中缺少.dll
- 从DLL中删除类的实例
- 如何包装第三方DLL在R中使用
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Python ctypes:不会按预期加载 dll
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL