C++ LPCTSTR to char*

前端 未结 3 1155
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 14:56

I am using visual studio 2010 MFC to build a C++ program. My program calls a DLL that is not apart of the project and it accepts a char*. I have a function that gets a string in

相关标签:
3条回答
  • 2021-01-25 15:34
    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

    0 讨论(0)
  • 2021-01-25 15:36

    In MFC the easiest is to convert through CStringA (provided that resulting buffer will be a read-only argument):

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

    Other options are available and were discussed:

    • c++ convert from LPCTSTR to const char *
    • How to convert from LPCTSTR to LPSTR?
    • WideCharToMultiByte, T2A macros etc.
    0 讨论(0)
  • 2021-01-25 16:00

    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).

    So the solution to your problem depends on whether you're using the UNICODE setting or not.

    If you are using it, you'll need to convert the string to a narrow string. Use CStringA to do this.

    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. You can do this by creating a copy using 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.

    0 讨论(0)
提交回复
热议问题