如何将CString转换为char *&? [英] how to convert CString to char *&?
本文介绍了如何将CString转换为char *&?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的visual c ++项目中,我想在char *&中转换CString对象。如何执行它?
项目是使用UNICODE支持构建的
In my visual c++ project i want to convert a CString object in char *&. how to perform it?
project is build with UNICODE support
推荐答案
好的,所以你调用的函数需要一个char *类型的参数&放;.这可能意味着,它采用char *形式的字符串作为输入,但希望能够自由地分配新缓冲区并通过此参数返回(因此引用)。
不幸的是,这个函数想要一个char *&而不是const char *&。这意味着,该函数还保留修改传入的字符串的权限。这意味着,您必须为该字符串分配一个新缓冲区,并且不能使用CString对象的缓冲区。
这是我要做的:
Ok, so a function you call wants an argument of type char*&. That probably means, it takes a character string in the form of a char* as input, but wants to have the freedom of allocating a new buffer and return that via this parameter (therefore the reference).
Unfortunately the function wants to have a char*& and not a const char*&. That means, the function reserves also the right to modify the string you are passing in. That means, you must allocate a new buffer for that string and you cannot use the buffer of your CString object.
Here is what I would do:
CString myString ("abcdef");
...
char* pBuffer = new char[myString.GetLenght() + 1]; // +1 for the NULL byte
strcpy (pBuffer, myString);
char* pArg = pBuffer; // copy pBuffer, because OtherFunction might
// return a different buffer in pArg and would
// overwrite our pBuffer
OtherFunction (pArg);
...
... look at what OtherFunction has returned via pArg
...
delete [] pBuffer;
...
... possibly you will have to delete [] pArg too, depending on the
... interface of OtherFunction.
如你所见,这是一个非常丑陋和危险的界面,我会尽量避免这种结构。
As you see, this is an extremely ugly and dangerous interface and I would try to avoid such constructs whenever possible.
on-stack only代码:):
The "on-stack only" code :) :
{
CString cszTest(_T("abc"));
#ifdef _UNICODE
USES_CONVERSION;
const char* pCh1(T2A(cszTest));
#else
const char* pCh1(cszTest);
#endif
const char*& pCh2(pCh1);
//..
}
// Actualy this argument is required by a function. That function is written by in another module.
另一个模块可以自己分配指针:),
请阅读其文档,然后检查此变体:
Another modul may allocate the pointer by itself :) ,
please read its documentation and then check this variant:
{
char* pChToBeAllocatedAndFilled(NULL);
pModul->Call(pChToBeAllocatedAndFilled);
CString cszResult(pChToBeAllocatedAndFilled); // convert it to UNICODE string
// Warning !
// Now we must know how the pointer has been allocated:
//free(pChToBeAllocatedAndFilled); // or
delete (pChToBeAllocatedAndFilled);
}
你好,
你不用担心*&,这意味着应该在该函数内修改给定指针中的数据。您只需将CString转换为char *并传递给该函数。但所有这些因素都取决于另一个模块的实现。
Hi,
You dont worry about "*&", it means the data in the given pointer should be modified inside that function. You just convert CString to char* and pass to that function. But all these factors depends on the "another module" implementation.
这篇关于如何将CString转换为char *&?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文