Reputation: 20644
I want to send a C# a list of string into C++ code using C++/CLI:
in C++, I put this in a constructor:
#include <string>
public:
MyAlgorithm(array<std::string>^ listAlgorithms);
But I got this compilation error:
error C2691: 'std::string' : a managed array cannot have this element type
And in the implementation I have:
MyAlgorithm(array<std::string>^ listAlgorithms)
{
pin_ptr<std::string> algorithms = &listAlgorithms[0];
std::string* unmanagedAlgorithms = algorithms;
}
And I got this error:
error C2440: 'initializing' : cannot convert from 'cli::interior_ptr<Type>' to 'cli::pin_ptr<Type>'
How should I correct them?
Thanks in advance.
Upvotes: 0
Views: 1018
Reputation: 16981
#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);
}
}
or
std::vector<std::string> unmanagedAlgorithms;
for each (auto algorithm in listAlgorithms)
{
unmanagedAlgorithms.push_back(msclr::interop::marshal_as<std::string>(algorithm));
}
or first string only
String^ managedAlgorithm = listAlgorithms[0];
std::string unmanagedAlgorithm = msclr::interop::marshal_as<std::string>(managedAlgorithm);
Upvotes: 2
Reputation: 50388
Y'all can't use classes when defining a managed array. If you're looking to use the std::string class, you're probably best going with something like std::vector.
PS: How come you don't do?
using namespace std;
Upvotes: 0