将unicode字符串从C#exe传递到C++;动态链接库 在C语言exe中使用这个函数,我尝试将Unicode字符串传递给我的C++ DLL: [DllImport("Test.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] public static extern int xSetTestString(StringBuilder xmlSettings); 这是C++ DLL方面的函数:
__declspec(dllexport)intxsetteststring(char*psettingxml) 在C#中调用函数之前,我先执行MessageBox.Show(string),它会正确显示所有字符。C++方面,我做的是:OutputDebugStringW((WCHARGET**)pStand);但这表明非ASCII字符已替换为“?”。请尝试:将unicode字符串从C#exe传递到C++;动态链接库 在C语言exe中使用这个函数,我尝试将Unicode字符串传递给我的C++ DLL: [DllImport("Test.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] public static extern int xSetTestString(StringBuilder xmlSettings); 这是C++ DLL方面的函数:,c#,c++,unicode,C#,C++,Unicode,__declspec(dllexport)intxsetteststring(char*psettingxml) 在C#中调用函数之前,我先执行MessageBox.Show(string),它会正确显示所有字符。C++方面,我做的是:OutputDebugStringW((WCHARGET**)pStand);但这表明非ASCII字符已替换为“?”。请尝试: [DllImport("Test.dll")] [return : MarshalAs(UnmanagedType.I4)] priva
[DllImport("Test.dll")]
[return : MarshalAs(UnmanagedType.I4)]
private static extern int externalTestString(
[MarshalAs(UnmanagedType. // The string type the C uses ansi/unicode/...) ] String st
);
public int TestString(String st // or string builder here)
{
// Perform input/output checks here + exception handling
}
确保C++函数在DLL之外可见(使用*O-DESPECIEDLExcel)。 如果可以看到函数及其名称,请检查using Dependes(VS2005附带)
如果C++函数不在类内,则可以使用未加密名称,如果使用Extn“C”,如果它们在类中,则需要指定一个具有依赖于已命名的名称的入口点。
< P>只需将原生DLL中的导出更改为:extern "C" __declspec(dllexport) int xSetTestString(wchar_t* pSettingsXML);
这样就行了
顺便说一句,你不能简单地做char*str1=(wchar\u t*)pSettingsXML代码>因为它不转换字符串。您需要使用
函数.< /P>代码是什么?代码> pStutsSXML X/<代码>?难道C++函数不应该使用<代码> W查尔特T*<代码>而不是<代码> char */Code >如果它接受Unicode?不一定。它可能使用UTF-8。预计设置为UTF-16,这是我认为微软内部使用的(不确定这是否正确)。如果是UTF-16,我同意@Johannes。它可能应该是将wcstombs
转换为wchar\u t*
。但在你的情况下,你不必这么做 注意:IMO的最佳实践是使用char*
而不是直接使用TCHAR*
,并将本机dll项目常规选项字符集设置为使用Unicode字符集。这将wchar\t*
定义为TCHAR*
Mirosoft本机使用两组函数:ANSI,使用1字节字符,标记为FunctionNameA;Unicode,使用2字节字符,标记为FunctionNameW。这个Unicode实际上是UTF-16wchar\u t*
UTF-8是一个多字节字符串,标准字符使用1字节,非标准字符使用2字节。若要将UTF-8转换为UTF-16,可以使用<代码> MulyByTeToWiDechar,在Windows上是16位的。我尝试了这个问题,但问题是相同的:[DllImport(“Test.dll”)][return:MarshalAs(UnmanagedType.I4)]public static extern int xSetTestString([MarshalAs(UnmanagedType.LPWStr)]String xmlSettings);你的C++字符串是什么类型?字符*wchar\u t*,标准::字符串?为什么要费心于wchar\u t
之类的东西呢?这只是一个宏,几十年前引入该宏是为了促进向Unicode的转换。新的代码,即使是C++,也应该从Unicode开始。为什么Windows程序员会麻烦FunctionA,甚至在最新的OS版本中也能运行输出,因为“新的代码,即使在C++中,也应该从Unicode开始”?看一看堆栈溢出。有多少q&A涉及char*和多少wchar\u t*?TCHAR