4

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

Jame
  • 21,150
  • 37
  • 80
  • 107

5 Answers5

4

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 as BSTR 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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

I think you have to convert that to something more C# friendly, like C-style array of char or wchar_t C-style strings. Here you can find an example of std::string marshaling. And here you'll find a discussion on how to marshal an std::vector.

Community
  • 1
  • 1
detunized
  • 15,059
  • 3
  • 48
  • 64
2

Try to use instead

C# part

[DllImport("MyDLL.dll")]
private static extern void GetCollection(ref string[] array, uint size);

C++ part

void GetCollection(string * array , uint size)

and fill array in GetCollection function

Stecya
  • 22,896
  • 10
  • 72
  • 102
1

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.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
1

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.

Community
  • 1
  • 1
yms
  • 10,361
  • 3
  • 38
  • 68