Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get array of string from Native Code(C++) in Managed Code(C#)

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

like image 915
Jame Avatar asked Dec 21 '22 16:12

Jame


1 Answers

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.

like image 56
David Heffernan Avatar answered Jan 22 '23 21:01

David Heffernan