【问题标题】:Passing a List<String^> from c++ to C#将 List<String^> 从 c++ 传递到 C#
【发布时间】:2013-06-11 14:07:55
【问题描述】:

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

到目前为止我的代码:

我要调用的c#类:

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# 程序集吗?

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

【问题讨论】:

    标签: c# c++-cli


    【解决方案1】:

    您缺少^

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

    您还需要将list.Add 切换为list-&gt;Add

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

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

    重要提示:此答案中的所有内容都适用于 .Net 中的引用类型(在 C# 中声明为 class,或在 C++/CLI 中声明为 ref classref struct)。它不适用于值类型(C# struct、C++/CLI value classvalue struct)。值类型(例如intfloatDateTime 等)总是在没有^ 的情况下声明和传递。

    【讨论】:

    • Grrr,我现在正在努力一个小时才能让它工作。错过了一个字符=D。非常感谢顺便说一句。它现在编译(-:
    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2013-11-03
    • 2018-08-04
    • 2018-01-11
    • 1970-01-01
    • 2015-11-20
    • 2015-07-02
    相关资源
    最近更新 更多