如何从托管代码(C#)中的本机代码(C++)获取字符串数组
有什么方法可以让我们从c++获取字符串集合到c#
C#代码
[DllImport("MyDLL.dll")]
private static extern List<string> GetCollection();
public static List<string> ReturnCollection()
{
return GetCollection();
}
C++代码
std::vector<string> GetCollection()
{
std::vector<string> collect;
return collect;
}
上面的代码仅用于示例,主要目的是从C++获取C#中的集合,并且将不胜感激
//Jame S
is there any way through which we can get the collection of string from c++ to c#
C# Code
[DllImport("MyDLL.dll")]
private static extern List<string> GetCollection();
public static List<string> ReturnCollection()
{
return GetCollection();
}
C++ Code
std::vector<string> GetCollection()
{
std::vector<string> collect;
return collect;
}
The code above is only for sample, the main aim is to get collection in C# from C++, and help would be appreciated
//Jame S
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有很多种方法可以解决这个问题,但它们都比您目前所拥有的要复杂得多。
将 C++ 中分配的字符串传递给 C# 的最简单方法可能是作为
BSTR
。这允许您在 C++ 中分配字符串并让 C# 代码取消分配它。这是您面临的最大挑战,因为BSTR
可以轻松解决它。由于您需要一个字符串列表,因此您可以将其更改为将其编组为
BSTR
数组。这是一种方式,这可能是我会采取的路线,但还有许多其他方法。There are a multitude of ways to tackle this, but they are all rather more complex than what you currently have.
Probably the easiest way to pass a string allocated in C++ to C# is as a
BSTR
. That allows you to allocate the string down in your C++ and let the C# code deallocate it. This is the biggest challenge you face and marshalling asBSTR
solves it trivially.Since you want a list of strings you could change to marshalling it as an array of
BSTR
. That's one way, it's probably the route I would take, but there are many other approaches.我认为您必须将其转换为更 C# 友好的内容,例如
char
的 C 样式数组或wchar_t
C 样式字符串。 在这里您可以找到std::string
封送的示例。以及此处您将找到有关如何封送std::vector
的讨论。I think you have to convert that to something more C# friendly, like C-style array of
char
orwchar_t
C-style strings. Here you can find an example ofstd::string
marshaling. And here you'll find a discussion on how to marshal anstd::vector
.尝试使用
C# 部分
C++ 部分
并在 GetCollection 函数中填充数组
Try to use instead
C# part
C++ part
and fill array in GetCollection function
我建议你将其更改为数组,然后对其进行封送。在 PInvoke 中编组数组要容易得多,事实上我根本不相信 C++ 类可以被编组。
I suggest you change it to array and then marshal it. Marshalling arrays is much easier in PInvoke and in fact I do not believe C++ classes classes can be marshalled at all.
我将在 C++ 中返回 BSTR 的 SAFEARRAY,并在 C# 中将其编组为字符串数组。您可以在此处查看如何使用 BSTR 的 safearray 如何构建指向 VARIANT 的指针的 SAFEARRAY?,或此处 http://www.roblocher.com /whitepapers/oletypes.aspx。
I would return a SAFEARRAY of BSTR in C++, and marshal it as an array of strings in C#. You can see how to use safearray of BSTR here How to build a SAFEARRAY of pointers to VARIANTs?, or here http://www.roblocher.com/whitepapers/oletypes.aspx.