C++ 将 CString 转换为字符数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/785187/
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 17:16:49  来源:igfitidea点击:

Convert CString to character array?

c++visual-c++charcstring

提问by yesraaj

How to convert CString in MFC to char[] (character array)

如何将 MFC 中的 CString 转换为 char[](字符数组)

回答by sharptooth

You use CString::GetBuffer() to get the TCHAR[] - the pointer to the buffer. If you compiled without UNICODE defined that's enough - TCHAR is same as char, otherwise you'll have to allocate a separate buffer and use WideCharToMultiByte() for conversion.

您使用 CString::GetBuffer() 来获取 TCHAR[] - 指向缓冲区的指针。如果编译时未定义 UNICODE 就足够了 - TCHAR 与 char 相同,否则您必须分配一个单独的缓冲区并使用 WideCharToMultiByte() 进行转换。

回答by Mark Eckdahl

I struggled with this, but what I use now is this: (UNICODE friendly)

我为此苦苦挣扎,但我现在使用的是:(UNICODE友好)

CString strCommand("My Text to send to DLL.");

CString strCommand("我要发送到 DLL 的文本。");

**

**

char strPass[256];
strcpy_s( strPass, CStringA(strCommand).GetString() );

**

**

// CStringA is a non-wide/unicode character version of CString This will then put your null terminated char array in strPass for you.

// CStringA 是 CString 的非宽/unicode 字符版本 这会将您的空终止字符数组放入 strPass 中。

Also, if you control the DLL on the other side, specifying your parameters as:

此外,如果您控制另一侧的 DLL,请将您的参数指定为:

const char* strParameter

const char* strParameter

rather than

而不是

charstrParameter*

字符字符串参数*

will "likely" convert CStrings for you with the default casting generally being effective.

将“可能”为您转换 CStrings,默认转换通常有效。

回答by Naveen

You can use GetBufferfunction to get the character buffer from CString.

您可以使用GetBuffer函数从 CString 中获取字符缓冲区。

回答by masche

Calling only the GetBuffer method is not sufficient, you'll need too copy this buffer to the array.

仅调用 GetBuffer 方法是不够的,您还需要将此缓冲区复制到数组中。

For example:

例如:

CString sPath(_T("C:\temp\"));
TCHAR   tcPath[MAX_PATH]; 
_tcscpy(szDisplayName, sPath.GetBuffer(MAX_PATH));

回答by ingconti

As noted elsewhere, if You need to port CString for warning C4840: non-portable f.

如别处所述,如果您需要为警告 C4840移植 CString :不可移植 f。

The quick, Unicode && Multibyte striong conversion is using:

快速的 Unicode && 多字节字符串转换使用:

static_cast

static_cast

sample:

样本:

    //was: Str1.Format( szBuffer, m_strName );
    Str1.Format(szBuffer, static_cast<LPCTSTR>(m_strName) );