从C ++传递一个函数指针由C#被称为 - 函数的参数包括宽字符的字符串(LPCWSTR) [英] Pass a function pointer from C++ to be called by C# - Arguments of functions include a wide char string (LPCWSTR)

查看:960
本文介绍了从C ++传递一个函数指针由C#被称为 - 函数的参数包括宽字符的字符串(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方法​​至极,我可以使用。这里的问题是,它从C#转换System.String要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)] 属性在为了您的委托声明的参数字符串即可转换成 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆