2012-03-22 70 views
0

我想用发送C#字符串列表到C++代码C++/CLI:发送从C#字符串的列表,以C++导致错误

在C++中,我把这个构造

#include <string> 

public: 
    MyAlgorithm(array<std::string>^ listAlgorithms); 

但我得到这个编译错误:

error C2691: 'std::string' : a managed array cannot have this element type

并在实施我:

MyAlgorithm(array<std::string>^ listAlgorithms) 
{ 
    pin_ptr<std::string> algorithms = &listAlgorithms[0]; 
    std::string* unmanagedAlgorithms = algorithms; 
} 

而且我得到了这个错误:

error C2440: 'initializing' : cannot convert from 'cli::interior_ptr<Type>' to 'cli::pin_ptr<Type>' 

我应该如何纠正?

在此先感谢。

回答

2
#include <string> 

#include <msclr/marshal_cppstd.h> 


MyAlgorithm(array<String^>^ listAlgorithms) 
{ 
    std::vector<std::string> unmanagedAlgorithms(listAlgorithms->Length); 
    for (int i = 0; i < listAlgorithms->Length; ++i) 
    { 
     auto s = listAlgorithms[i]; 
     unmanagedAlgorithms[i] = msclr::interop::marshal_as<std::string>(s); 
    } 

} 

std::vector<std::string> unmanagedAlgorithms; 
    for each (auto algorithm in listAlgorithms) 
    { 
     unmanagedAlgorithms.push_back(msclr::interop::marshal_as<std::string>(algorithm)); 
    } 

或第一串仅

String^ managedAlgorithm = listAlgorithms[0]; 
    std::string unmanagedAlgorithm = msclr::interop::marshal_as<std::string>(managedAlgorithm); 
+0

这看起来更好。我不是C++程序员。我可以问你关于你的代码。 unmanagedAlgorithm将只获得数组中的第一个元素吧?我想要unmangedAlgorithm的所有元素。我怎样才能做到这一点。可能,我的原始实施错了。谢谢 – olidev 2012-03-22 19:50:11

+0

检查当前变种 – 2012-03-22 20:34:13

+0

伟大的职位!非常感谢 – olidev 2012-03-22 20:46:44

0

在定义托管数组时,你们都不能使用类。如果你正在寻找使用std :: string类,你可能最好使用类似std :: vector的东西。


PS:你怎么没做到?

using namespace std; 
+0

你是对的,我应该使用命名空间 – olidev 2012-03-22 19:48:55