虽然我有相当多的C++使用经验,但我在C#方面还是个初学者。我当前的项目要求我在C++ DLL和C#图形用户界面之间来回传递数据。我主要是通过阅读stackoverflow上的回复来了解如何做到这一点的。不幸的是,我遇到了一个让我陷入困境的问题。动态链接库是使用g++ (gcc 4.2.1版,mingw32-2)编译的,而我正在使用Visual Studio2010来构建图形用户界面。
我的问题是,我可以从一些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());
}它在DLL头中是这样声明的:
extern "C" __declspec(dllexport) const char* mstLastError ();此函数不起作用,并返回空字符串:
[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 ));
}它在DLL中声明如下:
extern "C" __declspec(dllexport) const char* mstGetMetadata ( char* CStgMapName );使用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);它在DLL中声明如下:
extern "C" __declspec(dllexport) bool mstMapExists ( char* CStgMapName );此函数的工作方式与我预期的完全相同,因为它会在应该返回true/false的时候返回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);它在DLL中声明为:
extern "C" __declspec(dllexport) double mstGetResolution ( char* CStgName );你对发生了什么有什么想法吗?
谢谢和问候,迈克
发布于 2011-06-14 13:14:47
[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);https://stackoverflow.com/questions/6339223
复制相似问题