1

Am adding C# dll as reference in managed C++, and calling C# function in c++ which returns list of strings

C# code :

namespace ManagedCSharp
{   
  public static class ManagedClass
    {
        public static List<string> ShowValue(void)
        {
            List<string> x = new List<string>();
            x.Add("1");

            return x;

        }
    }
}

C++ Code:

public ref class DoWork
    {
    public:void GetListOfStrings(void)
        {           
           //here i need to collect list of strings returned from C#
            (??) =  ManagedCSharp::ManagedClass::ShowValue();   
        }
    };

Thanks in advance

2 Answers 2

1

If you are using managed C++ you can simply use:

List<string>^ myvar = ManagedCSharp::ManagedClass::ShowValue();

Of course you will have to add the using directive for System::Collections.

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

1 Comment

List<String^>^ myvar = ManagedCSharp::ManagedClass::ShowValue(); use System::Collections::Generic
0

First, I'd use C++/CLI for the interop. IMHO that makes life easy if you're mixing C++ and C# code.

Making namespaces explicit actually helps to make things clear in this case. C++ normally uses std::string, which can be converted to char*; C++/CLI uses System::String, which can be constructed (gcnew) from a System::Char* -- which are UTF-16 characters. To make the conversion, you need to apply an encoding, which can be found in System::Text::Encoding::ASCII::GetString. (or UTF-8 or whatever you use as your poison). It depends on what you put in your std::string.

Note that memory management in C++ and C# work quite differently. You still have to clean up your stuff on the unmanaged heap (if that applies); the constructor of System::String will simply copy the contents into a managed container.

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.