我正在尝试做一些非常简单的事情...在类中声明一个字符串,然后将其分配给在类构造函数中定义的另一个字符串的值。
我正在为非托管类“Unmanaged”使用托管包装器(使用托管包装器是因为我想在 C# 程序中使用它,而我正在使用的东西是非托管的,它的 .sln 文件不在我的控制)
如您所见,我尝试包含尽可能多的字符串标题。
#pragma once
#include <string>
#include <string.h>
#include <cstring>
#include <iostream>
using namespace std;
using namespace System;
using std::string;
namespace UnmanagedWrap {
public ref class Class1
{
// TODO: Add your methods for this class here.
public:
Unmanaged *pu; //pointer to the Unmanaged class
//the constructor will allocate the pointer pu
int a;
int b;
std::string filePath; //try CString() when get back
Class1(int a_In, int b_In, std::string filePath_In) : pu(new Unmanaged()) { //constructor
a = a_In;
b = b_In;
filePath = filePath_In; //trying to assign filePath to the inputted filePath_In.......
}; //end of constructor
这给了我 2 个错误:
第一个与行 std::string filePath;
1>c:\users\ngrace\documents\visual studio 2010\projects\unmanagedwrap\unmanagedwrap\UnmanagedWrap.h(21): error C4368: cannot define 'filePath' as a member of managed 'UnmanagedWrap::Class1': mixed types are not supported
第二个与 filePath = filePath_In;
行有关
1>c:\users\ngrace\documents\visual studio 2010\projects\unmanagedwrap\unmanagedwrap\UnmanagedWrap.h(25): error C2678: binary '=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
我很迷茫,因为我花了几个小时寻找答案......
我曾访问过的一些页面:
Including headers from an unmanaged C++ code inside C++/CLI code
(我会发布更多,但我需要至少 10 的声誉才能这样做......)
关于我为什么会收到这些错误的任何想法?
最佳答案
根据 Bo Persson 和用户 2666293 的信息,我被引导尝试了一些东西,最终得到了这个问题的答案。
您必须为托管字符串使用 System::String^ 类型。如果使用托管字符串并将其传递给非托管类中的方法,则必须将其转换为非托管字符串类型!
假设我们在 unmanaged 类中使用非托管字符串类型 std::string。
从 System::String^ 到 std:string 的转换必须使用:
auto unmannedString = msclr::interop::marshal_as<std::string>(managedString);
并在顶部引用了头文件:
#include <msclr/marshal_cppstd.h>
其中 managedString 是 System::String^ 类型
:)
关于Visual Studio 2010 上的 C++ : Cannot assign string to a string (mixed types are not supported),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381723/