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
  • 19,728
  • 34
  • 77
  • 103

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
  • 587,191
  • 41
  • 1,025
  • 1,442
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
  • 14,729
  • 3
  • 45
  • 63
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,338
  • 9
  • 70
  • 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
  • 78,844
  • 21
  • 155
  • 205
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,228
  • 3
  • 39
  • 67