Jan
Jan

Reputation: 139

Passing a List<String^> from c++ to C#

Not that experienced with c++, so requesting some help here. What I got is a .net dll and I'm writing a wrapper, so that the .net dll can be used later in c++ and vb6 projects.

My code so far:

c# class I want to call:

public class App
{
   public App(int programKey, List<string> filePaths)
   {
       //Do something
   }
}

my c++ project:

static int m_programKey;
static vector<std::string> m_fileNames;

void __stdcall TicketReportAPI::TrStart(int iProgramKey)
{
    m_programKey = iProgramKey;
};

void __stdcall TicketReportAPI::TrAddFile(const char* cFileName)
{
    string filename(cFileName);
    m_fileNames.push_back(filename);
}


void __stdcall TicketReportAPI::TrOpenDialog()
{

    if(m_fileNames.size()> 0)
    {

        List<String^> list = gcnew List<String^>();

        for(int index = 0; index < m_fileNames.size(); index++)
        {

            std::string Model(m_fileNames[index]);
            String^ sharpString = gcnew String(Model.c_str());

            list.Add(gcnew String(sharpString));
        }


        App^ app = gcnew App(m_programKey, list);

    }
    else
        App^ app = gcnew App(m_programKey);

}

If I'm trying to compile the c++ project I get following error:

App(int,System::Collections::Generic::List ^)': Conversion from 'System::Collections::Generic::List' to 'System::Collections::Generic::List ^' not possible

Is it possible to pass a managed List from c++ to .net c#? If not, what do you guys suggest me to pass a string array to my c# assembly?

Every help is appreciated, Thanks in advance.

Upvotes: 5

Views: 24953

Answers (1)

David Yaw
David Yaw

Reputation: 27864

You're missing a ^.

List<String^>^ list = gcnew List<String^>();
             ^-- right here

You'll also need to switch list.Add to list->Add.

You're using gcnew, which is how you create something on the managed heap, and the resulting type is a managed handle, ^. This is roughly equivalent to using new to create an object on the unmanaged heap, and the resulting type is a pointer, *.

Declaring a local variable of type List<String^> (without the ^) is valid C++/CLI: It makes the local variable use stack semantics. There's no C# equivalent to that variable type, so most of the .Net library doesn't work completely with it: For example, there's no copy constructors to deal with assignment to variables without the ^. All of the managed APIs expect parameters with types that have the ^, so most times, you'll want to use that for your local variables.

Important note: Everything in this answer applies to reference types in .Net (which are declared in C# as class, or in C++/CLI as ref class or ref struct). It does not apply to value types (C# struct, C++/CLI value class or value struct). Value types (such as int, float, DateTime, etc) are always declared & passed without the ^.

Upvotes: 15

Related Questions