C++ 将 System::String 转换为 Const Char *

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2093331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:04:47  来源:igfitidea点击:

Converting System::String to Const Char *

c++stringcharconst

提问by Reznor

I am using Visual C++ 2008's GUI creator to make a user interface. When a button is clicked, the following function is called. The content is supposed to create a file and name the file after the contents of the textbox "Textbox' with '.txt' at the end. However, that leads me to a conversion error. Here is the code:

我正在使用 Visual C++ 2008 的 GUI 创建器来制作用户界面。单击按钮时,将调用以下函数。内容应该创建一个文件,并在文本框“Textbox”的内容后命名文件,末尾带有“.txt”。但是,这导致我出现转换错误。这是代码:

private: System::Void Button_Click(System::Object^ sender, System::EventArgs^ e) { ofstream myfile (Textbox->Text + ".txt"); myfile.close(); }

private: System::Void Button_Click(System::Object^ sender, System::EventArgs^ e) { ofstream myfile (Textbox->Text + ".txt"); myfile.close(); }

Here is the error:

这是错误:

error C2664: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'System::String ^' to 'const char *'

错误 C2664:“std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)”:无法将参数 1 从“System::String ^”转换为“const char *” '

How can I do a conversion to allow this to go through?

我怎样才能进行转换以允许它通过?

回答by Timber Wolf

It's simple!

这很简单!

As you're using managed C++, use the include and operate like:

当您使用托管 C++ 时,请使用包含和操作,如:

#include <msclr/marshal.h>

...

void someFunction(System::String^ oParameter)
{
   msclr::interop::marshal_context oMarshalContext;

   const char* pParameter = oMarshalContext.marshal_as<const char*>(oParameter);

   // the memory pointed to by pParameter will no longer be valid when oMarshalContext goes out of scope
}

回答by jdehaan

I would use marshalling:

我会使用编组:

//using namespace System::Runtime::InteropServices;
const char* str = (const char*)(void*)
       Marshal::StringToHGlobalAnsi(Textbox->Text);
// use str here for the ofstream filename
Marshal::FreeHGlobal(str);

But note that you then use just Ansi strings. If you need unicode support you can use the widechar STL class wofstreamand PtrToStringChars(#include <vcclr.h>) to convert from System::String. In that case you do not need to free the pinned pointer.

但请注意,您随后仅使用 Ansi 字符串。如果您需要 unicode 支持,您可以使用宽字符 STL 类wofstreamPtrToStringChars( #include <vcclr.h>) 从System::String. 在这种情况下,您不需要释放固定指针。

回答by Sergey Teplyakov

#include <string>
#include <iostream>
#include <atlbase.h>
#include <atlconv.h>
#include <vcclr.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    String^ managedStr = gcnew String(L"Hello, Managed string!");
    //If you want to convert to wide string
    pin_ptr<const wchar_t> wch = PtrToStringChars(managedStr);
    std::wstring nativeWstr(wch);
    //if you want to convert to std::string without manual resource cleaning
    std::string nativeStr(CW2A(nativeWstr.c_str()));
    std::cout<<nativeStr<<std::endl;
    Console::WriteLine(L"Hello World");
    return 0;
}

回答by danger89

Thanks jdehaan. I little modified the code to use it with my 'normal' System::String's.

谢谢杰德汉。我几乎没有修改代码以将它与我的“正常” System::String 一起使用。

void MarshalNetToStdString(System::String^ s, std::string& os)
{
    using System::IntPtr;
    using System::Runtime::InteropServices::Marshal;

    const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer( );
    os = chars;
    Marshal::FreeHGlobal(IntPtr((void*)chars));
}

This is the way if you want to convert System:String -> std:string.

如果您想转换 System:String -> std:string,这就是方法。

回答by Meister Schnitzel

There is an really excellent article in MSDN about String conversions here:

MSDN 中有一篇关于字符串转换的非常出色的文章:

http://msdn.microsoft.com/en-us/library/ms235631%28vs.80%29.aspx

http://msdn.microsoft.com/en-us/library/ms235631%28vs.80%29.aspx

There are many samples to convert String from and to different types.

有许多示例可以将 String 从不同类型转换为不同类型。

回答by Ruddy

You can convert it to a CString and then add the extension to it.

您可以将其转换为 CString,然后向其中添加扩展名。

There is a built-in CString constructor which will allow this conversion to happen

有一个内置的 CString 构造函数,它将允许这种转换发生

Example:

例子:

CString(Textbox->Text)

In your specific case:

在您的具体情况下:

private: System::Void Button_Click(System::Object^ sender, System::EventArgs^ e) 
{
    ofstream myfile (CString(Textbox->Text) + ".txt"); 
    myfile.close(); 
}