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

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

1 Comment

That't won't work. Think about who allocates and deallocates the strings.
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.