如何将字符串转换为System :: Object?

时间:2013-08-30 20:34:01

标签: visual-c++ c++-cli

我有我的字符串:

myFunc(std::string text) {}

我希望将其转换为System :: Object。有点像...

array<Object^>^ inArgs = gcnew array<Object^>(2);
const char* ms;         
ms = text.c_str();
inArgs[1] = *ms;

除非我尝试将字符串输出,否则只会给我第一个字符。

...它不一定是std :: string。任何类型的字符串都可以。我正在做一个跨线程更新并试图传递一个字符串。

2 个答案:

答案 0 :(得分:3)

System :: String有一个接受const char *的构造函数。你对正确的代码页转换听起来并不挑剔,所以它可能会很好:

  std::string test("hello world");
  auto managed = gcnew String(test.c_str());
  Console::WriteLine(managed);

答案 1 :(得分:0)

这段代码可能远非正确的方法。我只是模仿我在C#中做的跨线程更新。实际答案来自评论。

init form,设置委托,启动第二个线程:

public ref class Form_1 : public System::Windows::Forms::Form
{
    public:
        CL* c;
        delegate System::Void CrossThreadUpdate(Object^ obj);
        CrossThreadUpdate^ crossThreadUpdate;
        void update(Object^ obj);
        Thread^ t;
        void updateTextArea(String^ text);
        void initCL();

        Form_1(void)
        {
            InitializeComponent();
            crossThreadUpdate = gcnew CrossThreadUpdate(this, &Form_1::update);
            t = gcnew Thread(gcnew ThreadStart(this, &Form_1::initCL));
            t->Start();
            //
            //TODO: Add the constructor code here
            //
        }

线程做了它的事情然后让我们知道它完成了

void Form_1::initCL() 
{
    c = new CL();
    updateTextArea("CL READY");
}

更新表单

void Form_1::update(Object^ obj) {
        array<Object^>^ arr = (array<Object^>^)obj;
        int^ op = safe_cast<int^>(arr[0]);

        switch(*op)
        {
            case 1:
                String^ text = safe_cast<String^>(arr[1]);
                wstring stringConvert = L"";
                MarshalString(text, stringConvert);
                wcout << stringConvert << endl;
                this->textBox1->Text += text + "\r\n";
                break;
        }
    }

    void Form_1::updateTextArea(String^ text) {
        array<Object^>^ args = gcnew array<Object^>(1);
        array<Object^>^ inArgs = gcnew array<Object^>(2);
        inArgs[0] = 1;
        inArgs[1] = text;
        args[0] = inArgs;
        this->Invoke(crossThreadUpdate, args);
    }