C# 调用本机 C++所有功能:使用什么类型?
我想制作一个原生 C++,所有这些都可以从 C# 项目中使用。
- 如果我想将 C# 中的字符串传递给 C++ 中的函数,我应该使用什么参数?
- 我知道 C# 字符串使用 Unicode,因此我尝试使用 wchar_t * 作为该函数,但它不起作用;我尝试捕获从被调用函数引发的任何异常,但没有引发异常。
- 我还想返回一个字符串,以便我可以测试它。
C++ 函数如下:
DECLDIR wchar_t * setText(wchar_t * allText) {
return allText;
}
C# 代码如下:
[DllImport("firstDLL.Dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern string setText(string allText);
var allText= new string('c',4);
try {
var str1 = setText(allText);
}
catch (Exception ex) {
var str2 = ex.Message;
}
C++ 函数的返回类型应该使用什么类型,以便我可以从 C# 中以 string[]
返回类型调用它? 同样的问题,但是 C# 中函数的参数是 string[] 吗?
I want to make a native C++ all that can be used from a C# project.
- If I want to pass a string from C# to the function in the C++ all, what parameter should I use?
- I know that C# strings use Unicode, so I tried wchar_t * for the function but it didn't work; I tried catching any exceptions raised from the called function, but no exception was thrown.
- I also want to return a string so I can test it.
The C++ function is the following:
DECLDIR wchar_t * setText(wchar_t * allText) {
return allText;
}
The C# code is the following:
[DllImport("firstDLL.Dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern string setText(string allText);
var allText= new string('c',4);
try {
var str1 = setText(allText);
}
catch (Exception ex) {
var str2 = ex.Message;
}
What type should I use for the C++ function's return type, so that I can call it from C# with a return type of string[]
?
the same Q but for the parameter of the function to be string[] in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可能会使用 COM BSTR 来完成此操作,并避免混乱缓冲区分配。像这样:
C++
C#
BSTR 是本机 COM 字符串类型。此处使用它的优点是可以使用 COM 分配器在接口的本机端(在 C++ 中)分配内存,然后使用相同的分配器在接口的托管端销毁内存。 P/Invoke 编组器了解有关 BSTR 的所有内容并为您处理一切。
虽然您可以通过传递缓冲区长度来解决这个问题,但它会导致相当混乱的代码,这就是我更喜欢 BSTR 的原因。
对于你的第二个问题,关于 P/Invoking
string[]
,我想你会从 Chris Taylor 对 Stack Overflow 上另一个问题的回答。I'd probably do it with a COM BSTR and avoid having to mess with buffer allocation. Something like this:
C++
C#
BSTR is the native COM string type. The advantage of using it here is that the memory can be allocated on the native side of the interface (in C++) with the COM allocator, and then destroyed on the managed side of the interface with the same allocator. The P/Invoke marshaller knows all about BSTR and handles everything for you.
Whilst you can solve this problem by passing around buffer lengths, it results in rather messy code, which is why I have a preference for BSTR.
For your second question, about P/Invoking
string[]
, I think you'll find what you need from Chris Taylor's answer to another question here on Stack Overflow.一个非常有用的网站,其中包含工具和很多好的信息是http://pinvoke.net/
它可能对你有帮助。
A very useful site with tooling and lots of good information is http://pinvoke.net/
It might help you.
C++
C#
C++
C#