Visual Studio 2010 上的 C++ : Cannot assign string to a string (mixed types are not supported)

标签 c++ string visual-studio-2010 assign managed

我正在尝试做一些非常简单的事情...在类中声明一个字符串,然后将其分配给在类构造函数中定义的另一个字符串的值。

我正在为非托管类“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

Mixed types are not supported

(我会发布更多,但我需要至少 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>

其中 ma​​nagedString 是 System::String^ 类型

:)

关于Visual Studio 2010 上的 C++ : Cannot assign string to a string (mixed types are not supported),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381723/

相关文章:

c - ANSI C 拆分字符串

html - 如何对齐表格

c++ - try, throw , catch 二维数组不起作用

c++ - mkl_free() 问题

C++如何触发PostMessage在另一个线程中进行

c# - SQL参数编辑

c# - 将 Kinect 应用程序连接到 Kinect Studio

c++ - 如何更改 CListBox/CComboBox 中特定项目的字体

javascript - 获取字符串的最后一部分

python : UTF-8 : How to count number of words in UTF-8 string?