简体   繁体   中英

How to return List of strings from C# to Managed c++

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM