我们正在挖掘一些非常古老的C++/CLI-Code(旧语法.NET Beta),看到类似的东西有点惊讶:
System::String ^source("Test-String");
printf("%s", source);
Run Code Online (Sandbox Code Playgroud)
程序正确输出
Test-String
Run Code Online (Sandbox Code Playgroud)
我们想知道,为什么可以将托管字符串源传递给printf- 更重要的是:为什么它可以工作?我不认为它是编译器的一些便利功能,因为以下不起作用:
System::String ^source("Test-String");
char pDest[256];
strcpy(pDest, source);
Run Code Online (Sandbox Code Playgroud)
这会产生(某种程度上预期的)编译错误,表示System::String^无法转换为const char*.因此,我唯一真正的解释是,将托管引用传递给va_list超过了所有编译器检查,并将本机代码用于使用指向托管堆的指针.由于在内存中System::String表示类似于char-Array,printf可能有效.或者编译器转换为a pin_ptr并将其传递给printf.
我不希望它自动编组String^to char*,因为这会导致内存泄漏,而不会引用实际的内存地址.
我们知道这不是一个好的解决方案,后来的Visual Studio-Versions引入的各种编组方法提供了一种更好的方法,但理解这里实际发生的事情会非常有趣.
谢谢!
可能重复:
需要将String ^转换为char*
我一直在寻找这个解决方案,但我找不到具体的内容.我在Visual Studio C++,Windows窗体应用程序中工作.我需要将String^值转换为char数组.我从储值TextBox在String^:
String^ target_str = targetTextBox->Text;
// lets say that input is "Need this string"
Run Code Online (Sandbox Code Playgroud)
我需要转换它String^并获得类似于此的输出:
char target[] = "Need this string";
Run Code Online (Sandbox Code Playgroud)
如果它被定义为char target[]可行,但我想从中获取此值TextBox.
我尝试过编组,但它没有用.有没有解决方法怎么做?
我已经找到了如何转换std::string为char数组所以如何解决这个问题的另一种方法是转换String^为std::string但我也遇到了这个问题.
如何将'String ^'转换为'const char*'?
String^ cr = ("netsh wlan set hostednetwork mode=allow ssid=" + this->txtSSID->Text + " key=" + this->txtPASS->Text);
system(cr);
Run Code Online (Sandbox Code Playgroud)
错误:
1 IntelliSense: argument of type "System::String ^" is incompatible with parameter of type "const char *"
Run Code Online (Sandbox Code Playgroud)