在发布版本中,将c#字符串传递到c++ dll失败

pass C# string to C++ dll fails in Release build

本文关键字:字符串 失败 dll c++ 布版本 版本      更新时间:2023-10-16

我有一个c++ dll与简单的函数,如

#ifdef BUILDING_THE_DLL
#define EXPORTED __declspec(dllexport)
#else
#define EXPORTED __declspec(dllimport)
#endif
 ...
EXPORTED void AddSetting(char *key, char *value)

和带有函数声明的c#项目:

[DllImport("pers.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void AddSetting(string key, string value);

当c#项目在调试模式下构建时,一切都工作得很好。在发布版本中,会触发一个异常:"试图以不正确的格式加载程序。"

任何想法?

UPD:在c#项目中,平台目标在Debug模式下设置为x86,在Release中设置为Any CPU。我在发布版中改成了x86,这就是解决方案。非常感谢Matt。

默认情况下需要指定使用ansi格式的字符串。它是unicode。应该是:

[DllImport("pers.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet::Ansi)]
public static extern void AddSetting(string key, string value);

同样,如果函数"AddSetting"修改字符串,你需要在c#中使用StringBuilder。