如何将 PWCHAR 传递给 C++来自 C# 的 dll
我有一个用 C++ 编写的 dll,我想从 C# 调用它。该函数输出outputChar和deadChar,deadChar变量也由C++函数读取。
我尝试以不同的方式从 C# 调用函数,但每次都收到 AccessViolationException:“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”
C++ dll:
extern "C" _declspec (dllexport) int convertVirtualKeyToWChar(int virtualKey, PWCHAR outputChar, PWCHAR deadChar);
C# 代码 1:
[DllImport("keylib.dll")]
static extern int convertVirtualKeyToWChar(int virtualKey,
StringBuilder output,
StringBuilder deadchar);
C# 代码 2:
static extern int convertVirtualKeyToWChar(int virtualKey,
out char output,
ref char deadchar);
I have an dll written in C++, and I want to call it from C#. The function outputs outputChar and deadChar, the deadChar variable is also read by the C++ function.
I tried to call function from C# in different ways, but all time I got AccessViolationException: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
C++ dll:
extern "C" _declspec (dllexport) int convertVirtualKeyToWChar(int virtualKey, PWCHAR outputChar, PWCHAR deadChar);
C# code 1:
[DllImport("keylib.dll")]
static extern int convertVirtualKeyToWChar(int virtualKey,
StringBuilder output,
StringBuilder deadchar);
C# code 2:
static extern int convertVirtualKeyToWChar(int virtualKey,
out char output,
ref char deadchar);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:函数
convertVirtualKeyToWChar
的两个PWCHAR
参数不明确。它们可以是指向单个WCHAR
的指针,也可以是指向WCHAR
字符串的指针。给定函数和参数的名称,此答案假设它们是指向单个WCHAR
的指针。您想使用以下内容:
您的崩溃由两个原因引起:
DllImport
默认为 ANSI 字符集和 StdCall 调用约定。您的 C++ DLL 没有指定任何调用约定,因此它将默认为 CDecl。请参阅 DllImportAttribute.CallingConvention 和 DllImportAttribute.CharSet
Note: The two
PWCHAR
arguments to your functionconvertVirtualKeyToWChar
are ambiguous. They could be pointers to a singleWCHAR
or pointers to aWCHAR
string. Given the name of the function and arguments, this answer assumes they are pointers to a singleWCHAR
.You want to use the following:
Your crash is caused by two reasons:
DllImport
defaults to the ANSI character set and StdCall calling convention. Your C++ DLL does not specify any calling convention, so it will default to CDecl.See DllImportAttribute.CallingConvention and DllImportAttribute.CharSet
这是在黑暗中进行的尝试,所以买者自负...
将单元素数组传递给每个
char[]
参数。This is a stab in the dark, so caveat emptor...
Pass a single-element array to each
char[]
parameter.尝试一下(请记住,如果在 Alloc 和 Free 之间引发异常,您将泄漏内存,因此请构建一些错误处理):
Try this (bearing in mind that if an exception is thrown between Alloc and Free you will leak memory, so build some error handling in):