在C++ DLL和C#GUI之间传递数据时的结果不一致

Mik*_*tts 6 c# c++ dll

虽然我对C++有着丰富的经验,但我仍然是C#的初学者.我当前的项目要求我在C++ DLL和C#GUI之间来回传递数据.我主要通过阅读stackoverflow上的响应来学习如何做到这一点.不幸的是,我遇到了一个让我陷入困境的问题.DLL使用g ++(gcc版本4.2.1 mingw32-2)编译,我使用Visual Studio 2010来构建GUI.

我的问题是我可以从一些DLL函数而不是其他函数中获取数据到C#.令人抓狂的是它似乎不一致,因为有些功能有效,有些则无效.为了向您展示我的意思,我在下面提供了C#导入代码和C++导出声明.我真的很感激这方面的一些建议,因为我真的不知道如何解决这个问题.

这个功能很好用:

[DllImport("mstTools.dll", EntryPoint = "mstLastError", CallingConvention =    CallingConvention.Cdecl)]
private static extern IntPtr LastError();

public static string mstGetLastError()
{
  return Marshal.PtrToStringAnsi(LastError());
}
Run Code Online (Sandbox Code Playgroud)

它在DLL头中声明如下:

extern "C" __declspec(dllexport) const char* mstLastError ();
Run Code Online (Sandbox Code Playgroud)

此函数不起作用并返回空字符串:

[DllImport("mstTools.dll", EntryPoint = "mstGetMetadata", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr GetMetadata([MarshalAs(UnmanagedType.LPStr)]string StgMapName);

public static string mstGetMetadata( string StgMapName )
{
  return Marshal.PtrToStringAnsi(GetMetadata( StgMapName ));
}
Run Code Online (Sandbox Code Playgroud)

它在DLL中声明如下:

extern "C" __declspec(dllexport) const char* mstGetMetadata ( char* CStgMapName );
Run Code Online (Sandbox Code Playgroud)

使用Visual Studio调试器,我可以看到导入的DLL函数(GetMetadata)返回null.

相反,返回bool工作的函数,例如:

[DllImport("mstTools.dll", EntryPoint = "mstMapExists", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool mstMapExists([MarshalAs(UnmanagedType.LPStr)]string StgMapName);
Run Code Online (Sandbox Code Playgroud)

在DLL中声明如下:

extern "C" __declspec(dllexport) bool mstMapExists ( char* CStgMapName );
Run Code Online (Sandbox Code Playgroud)

这个函数完全按照我的预期工作,因为它应该返回true/false.

但是返回double的函数返回NaN:

[DllImport("mstTools.dll", EntryPoint = "mstGetResolution", CallingConvention =CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.R8)]
public static extern double mstGetResolution([MarshalAs(UnmanagedType.LPStr)]string StgMapName);
Run Code Online (Sandbox Code Playgroud)

它在DLL中声明为:

extern "C" __declspec(dllexport) double mstGetResolution ( char* CStgName );
Run Code Online (Sandbox Code Playgroud)

关于发生了什么的任何想法?

谢谢和问候,迈克

Wal*_*eed 1

[DllImport("mstTools.dll", EntryPoint = "mstGetResolution")]
public static extern decimal mstGetResolution([In]string StgMapName);

[DllImport("mstTools.dll", EntryPoint = "mstGetMetadata")]
private static extern IntPtr GetMetadata([In]string StgMapName);
Run Code Online (Sandbox Code Playgroud)