开发者

Conversion from CString to char*/TCHAR*

开发者 https://www.devze.com 2023-03-30 03:10 出处:网络
I am well aware of techniques to convert CString to a C-style character. One of them is to use strcpy/_tcscpy, and others include using CStrBuf.

I am well aware of techniques to convert CString to a C-style character. One of them is to use strcpy/_tcscpy, and others include using CStrBuf.

The problem:

char Destination[100];
CStringA Source; // A is for simplicity and explicit ANSI specification.

Source = "This is source string."

Now I want this:

Destination = Source;

To happen automatically. Well, that logically means writing a conversion operator in CString class. But, as implicit as it is, I dont have privileges to change the CString class.

I thought of writing a global conversion opertor and global assignment operator. But it doesnt work:

operator char* (const CStringA&); // Error - At least must be class-type
operator = ... // Won't work either - cannot be global.

Yes, it is definitely possible to write function (preferably a templated one). But that involves calling the function,开发者_运维知识库 and it is not smooth as assignment operator.


You cannot assign to arrays. This makes what you want impossible. Also, honestly, it's a pretty wrong thing to do - a magic-number-sized buffer?


Well, I don't want to say that this is in any way recommendable, but you could hijack some lesser-used operator for a quick hack:

void operator<<=(char * dst, const std::string & s)
{
  std::strcpy(dst, s.c_str());
}

int main()
{
  char buf[100];
  std::string s = "Hello";

  buf <<= s;
}

You could even rig up a moderately safe templated version for statically sized arrays:

template <typename TChar, unsigned int N>
inline void operator<<=(TChar (&dst)[N], const std::string & s)
{
  std::strncpy(dst, s.c_str(), N);
}


An operator on CString won't solve the problem since you need to copy to Destination buffer although this assignment would change the value of Destination, which is impossible.

Somehow, you need an operator to achive this line:

strcpy(Destination, LPCSTR(Source)); // + buffer overflow protection

As you can see, converting Source is only half way. You still need to copy to the destination buffer.

Also, I wouldn't recommend it because the line Destination = Source is completely misleading in regard of the char[] semantics.

The only possible such assignment would be an initialisation of Destination:

char Destination[100] = Source;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号