传递来自 C++ 的函数指针以供 C# 调用 - 函数参数包括宽字符字符串 (LPCWSTR) [英] Pass a function pointer from C++ to be called by C# - Arguments of functions include a wide char string (LPCWSTR)
问题描述
我正在编写一个供本机 C++ 应用程序使用的 C# 库.我使用 C++/CLI 作为互操作性机制.
I am writing a C# library to be used by native C++ application. I am using C++/CLI as the Interoperability mechanisim.
我需要将回调函数从 C++ 传递到 C#(使用 C++/CLI 作为中间层).C# 库需要使用以零结尾的宽字符字符串调用 C++ 函数;即回调函数的原型是
I require to pass a callback function from C++ to C# (using C++/CLI as the intermediate layer). C# library needs to call the C++ function with a zero terminated string of wide characters; i.e. the prototype of the callback function is
Func(LPCWSTR pszString);
Func(LPCWSTR pszString);
还有其他参数,但它们对本次讨论无关紧要.
There are other parameters but they are immaterial for this discussion.
我在网上搜索并找到了我可以使用的 Marshal.GetDelegateForFunctionPointer 方法.问题在于它将 System.String 从 C# 转换为 char* 而不是我正在寻找的 wchar_t*.
I searched net and found Marshal.GetDelegateForFunctionPointer Method wich I can use. The problem with this is that it converts System.String from C# to char* and not wchar_t* which I am looking for.
此外,如果可能,实现此代码示例(包括 C++/CLI 部分)的最佳方法是什么.C++/CLI dll 依赖于 C# dll.方法需要同步调用.
Also, what is the best method of achieving this- code example including the C++/CLI portion, if possible. C++/CLI dll is dependent on C# dll. Method needs to be called synchronously.
推荐答案
GetDelegateForFunctionPointer
可以使用,但是你需要添加一个 [MarshalAs(UnmanagedType.LPWStr)]
属性到您的委托声明中的参数,以便将 String
转换为 wchar_t*
:
GetDelegateForFunctionPointer
will work, but you need to add a [MarshalAs(UnmanagedType.LPWStr)]
attribute to the parameter in your delegate declaration in order for String
to get converted into wchar_t*
:
delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] string foo)
IntPtr func = ...;
MyDelegate del = (MyDelegate)Marshal.GetDelegateForFunctionPointer(func,
typeof(MyDelegate));
要传递一个可修改的字符串,请提供一个StringBuilder
.您需要为非托管函数显式保留空间以供使用:
To pass a modifiable string, give a StringBuilder
. You need to explicitly reserve space for the unmanaged function to work with:
delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] StringBuilder foo)
StringBuilder sb = new StringBuilder(64); // reserve 64 characters.
del(sb);
这篇关于传递来自 C++ 的函数指针以供 C# 调用 - 函数参数包括宽字符字符串 (LPCWSTR)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!