获取 char 变量的值到 C++ 中的 ref class 字符串 (Visual Studio)
Get value of char variable into a ref class String in C++ (Visual Studio)
我现在正在为 Visual Studio 2017 的程序按钮编写一些代码。我有一个 char 变量(例如 char c = 't'),然后我想要按钮标签(即 button.Text) 由 c 的变化来修改。 button.Text 是引用 class 字符串属性。
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 属性是一个引用字符串 class,而不是字符串 class。
C++ convert from 1 char to string?
所以你能帮我解决我的问题吗?谢谢!
我想你要找的是'Overview of Marshalling in 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)
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.
我现在正在为 Visual Studio 2017 的程序按钮编写一些代码。我有一个 char 变量(例如 char c = 't'),然后我想要按钮标签(即 button.Text) 由 c 的变化来修改。 button.Text 是引用 class 字符串属性。
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 属性是一个引用字符串 class,而不是字符串 class。 C++ convert from 1 char to string?
所以你能帮我解决我的问题吗?谢谢!
我想你要找的是'Overview of Marshalling in 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)
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.