CString到char * [英] CString to char*

查看:221
本文介绍了CString到char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在大多数代码中使用CString类。但是有时我们需要转换为char *。目前我们一直在使用variable.GetBuffer(0),这似乎工作(这主要发生在传递Csting到一个函数,其中的函数需要一个char *)。

We are using the CString class throughout most of our code. However sometimes we need to convert to a char *. at the moment we have been doing this using variable.GetBuffer(0) and this seems to work ( this mainly happens when passing the Csting into a function where the function requires a char *). The function accepts this and we keep going.

然而,我们最近担心这是如何工作的,以及是否有更好的方法。

However we have lately become worried about how this works, and whether there is a better way to do it.

我理解它的工作方式是将一个字符指针传递到指向CString中的第一个字符的函数,并且一切正常。

The way i understand it to work is it passes a char pointer into the function that points at the first character in the CString and all works well.

我猜我们只是担心内存泄漏或任何不可预见的情况,这可能不是一个好主意。

I Guess we are just worried about memory leaks or any unforseen circumstances where this might not be a good idea.

推荐答案

如果函数只需要读取字符串而不修改它,请将其改为接受 const char * ,而不是 char * CString 会自动转换为你,这是大多数MFC函数的工作,它真的很方便。 (实际上MFC使用 LPCTSTR ,这是 const TCHAR * 的同义词 - 适用于MBC和Unicode构建)。

If your functions only require reading the string and not modifying it, change them to accept const char * instead of char *. The CString will automatically convert for you, this is how most of the MFC functions work and it's really handy. (Actually MFC uses LPCTSTR, which is a synonym for const TCHAR * - works for both MBC and Unicode builds).

如果您需要修改字符串, GetBuffer(0)是非常危险的 -

If you need to modify the string, GetBuffer(0) is very dangerous - it won't necessarily allocate enough memory for the resulting string, and you could get some buffer overrun errors.

正如其他人所提到的,你需要使用 ReleaseBuffer 之后 GetBuffer 。你不需要这样做,转换为 const char *

As has been mentioned by others, you need to use ReleaseBuffer after GetBuffer. You don't need to do that for the conversion to const char *.

这篇关于CString到char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆