简体   繁体   English

C ++ LPCTSTR转换为char *

[英]C++ LPCTSTR to char*

I am using visual studio 2010 MFC to build a C++ program. 我正在使用Visual Studio 2010 MFC构建C ++程序。 My program calls a DLL that is not apart of the project and it accepts a char*. 我的程序调用一个不属于项目的DLL,它接受一个char *。 I have a function that gets a string in a format of LPCTSTR. 我有一个函数,该函数以LPCTSTR格式获取字符串。 I have been on google for about two hours now, and no solution found. 我已经在Google上待了大约两个小时,但没有找到解决方案。 How do I convert form a MFC LPCTSTR to a char*. 如何将MFC LPCTSTR格式转换为char *。 Everything I have found either does not work, or just does not compile. 我发现的所有内容都不起作用,或者只是无法编译。

In MFC the easiest is to convert through CStringA (provided that resulting buffer will be a read-only argument): 在MFC中,最简单的方法是通过CStringA进行转换(前提是生成的缓冲区将是只读参数):

LPCTSTR pszA = ...
CStringA sB(pszA);
const char* pszC = sB;
char* pszD = const_cast<char*>(pszC);

Other options are available and were discussed: 其他选项可用并进行了讨论:

LPCTSTR patientName= L"";
CStringA sB(patientName);
const char* pszC = sB; 

DcmFileFormat fileformat;
//Type casting below to const char * str
OFCondition status = fileformat.loadFile(((LPCSTR)(CStringA)str));
if (status.good())
{
    if (fileformat.getDataset()->findAndGetString(DCM_PatientName, pszC).good())             
    {
        //Type casting from const char * to LPCTSTR
        m_List.InsertColumn(4, LPCTSTR(pszC) , LVCFMT_LEFT, 100); 
    }
 }

This was the way i used to typecast the variables 这就是我用来类型化变量的方式

LPCTSTR is either defined as a const wchar_t * or a const char * depending on whether your project defined the preprocessor symbol UNICODE (or _UNICODE , I forget which one MFC uses). LPCTSTR可以定义为const wchar_t *const char *具体取决于您的项目是否定义了预处理器符号UNICODE (或_UNICODE ,我忘记了一个MFC使用的符号)。

So the solution to your problem depends on whether you're using the UNICODE setting or not. 因此,解决问题的方法取决于您是否使用UNICODE设置。

If you are using it, you'll need to convert the string to a narrow string. 如果使用它,则需要将字符串转换为字符串。 Use CStringA to do this. 使用CStringA执行此操作。

If you're not using UNICODE you'll need to make a copy that is mutable and pass it to the DLL, in case it wants to modify the string. 如果您不使用UNICODE,则需要制作一个可变的副本,并将其传递给DLL,以防它想要修改字符串。 You can do this by creating a copy using CString . 您可以通过使用CString创建一个副本来做到这一点。

In either case, once you have a copy in a CString object then use the GetBuffer method to get a mutable pointer to the string, call the DLL function and then call ReleaseBuffer after the call. 无论哪种情况,一旦在CString对象中有一个副本,然后使用GetBuffer方法获取指向该字符串的可变指针,则调用DLL函数,然后在调用之后调用ReleaseBuffer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM