将List <string ^>从c ++传递到C#</string ^>

时间:2013-06-11 14:07:55

标签: c# c++-cli

不熟悉c ++,所以请求一些帮助。 我得到的是一个.net dll,我正在编写一个包装器,以便.net dll可以在以后的c ++和vb6项目中使用。

到目前为止我的代码:

c#c​​lass我想打电话:

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

我的c ++项目:

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);

}

如果我正在尝试编译c ++项目,我会收到以下错误:

App(int,System :: Collections :: Generic :: List ^)':从'System :: Collections :: Generic :: List'转换为'System :: Collections :: Generic :: List ^'不可能

是否可以将托管列表从c ++传递到.net c#? 如果没有,你们有什么建议我将字符串数组传递给我的c#assembly?

感谢每一位帮助,提前致谢。

1 个答案:

答案 0 :(得分:12)

您错过了^

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

您还需要将list.Add切换为list->Add

您正在使用gcnew,这是您在托管堆上创建内容的方式,结果类型是托管句柄^。这大致相当于使用new在非托管堆上创建对象,结果类型是指针*

声明类型为List<String^>的局部变量(不带^)是有效的C ++ / CLI:它使局部变量使用堆栈语义。没有C#等效于该变量类型,因此大多数.Net库都不能完全使用它:例如,没有复制构造函数来处理没有^的变量赋值。所有托管API都需要具有^类型的参数,因此大多数情况下,您都希望将其用于本地变量。

重要说明:此答案中的所有内容都适用于.Net中的引用类型(在C#中声明为class,或在C ++ / CLI中声明为ref classref struct)。它不适用于值类型(C#struct,C ++ / CLI value classvalue struct)。值类型(例如intfloatDateTime等)始终声明为&amp;在没有^的情况下通过。