在C ++中将char变量的值获取到ref类字符串中(Visual Studio)

时间:2018-12-03 13:50:35

标签: string class c++-cli

我现在正在Visual Studio 2017上为程序的按钮编写一些代码。我有一个char变量(例如char c ='t'),然后我想要按钮标签(即button.Text)由c的修改修改。 button.Text是ref类的String属性。

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
{
    char c = 't';
    String^ xyz;

    button1->Text = xyz;
}

In VisualStudio 1

In VisualStudio 2

我已经尝试过这种解决方案,但是它无法正常工作,因为button.Text属性是一个引用字符串类,而不是字符串类。  C++ convert from 1 char to string?

那么您能帮我解决我的问题吗?谢谢!

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是“ C ++中的编组概述”:https://docs.microsoft.com/en-us/cpp/dotnet/overview-of-marshaling-in-cpp?view=vs-2017

例如:

#include "msclr/marshal.h"
using namespace System;
using namespace msclr::interop;
int main()
{
    char c = 't';
    String^ sref = marshal_as<String^>(&c);
    Console::WriteLine(sref);
    return 0;
}

注意:如果在字符串中嵌入了NULL,则不能保证将字符串编组的结果。嵌入的NULL可能导致字符串被截断或可能被保留。 (Source

答案 1 :(得分:0)

with accordance with @HansPassant advice:
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
{
  Char c = 't';// Remeber Char is managed one 
  button1->Text = gcnew String(c.ToString());
}
  This way you can avoid marshalling and other costly interop operations
  unless you want to use managed and unmanaged code together.