How to get array of string from Native Code (C ++) in managed code (C #)

is there any way with which we can get a set of strings 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 above code is for sample only, the main goal is to get collection in C # from C ++, and help will be appreciated

// Jame S

+4
source share
5 answers

There are many ways to solve this problem, but they are all more complex than what you currently have.

Probably the easiest way to pass a string allocated in C ++ to C # is through BSTR . This allows you to highlight a line in C ++ and allow C # code to free it. This is the biggest problem you encounter and sorting as BSTR resolves it trivially.

Since you need a list of strings, you can change its sorting as a BSTR array. This is one way, this is probably the route I would take, but there are many other approaches.

+4
source

Try using 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 the array in the GetCollection function

+3
source

I think you need to convert this to something more C # friendly, such as a C-style array of char strings or wchar_t C-style. Here you can find an example of std::string marshaling. And here you will find a discussion on how to marshal std::vector .

+3
source

I suggest you change it to an array and then marshal. Marshalling arrays is much simpler in PInvoke, and in fact I do not believe that C ++ class classes can be configured at all.

+1
source

I would return SAFEARRAY from BSTR in C ++ and marshal it as an array of strings in C #. You can see how to use saferray BSTR here. How to create SAFEARRAY pointers to VARIANT? or here http://www.roblocher.com/whitepapers/oletypes.aspx .

+1
source

Source: https://habr.com/ru/post/1343161/


All Articles