Search code examples
c++unicodemfctextrange

Convert TEXTRANGE structure's lpstrtext member to MultiByteCharacterSet


I have two different projects in C++, one compiles to a static library and uses Unicode character encoding as it has to support multiple languages (Spell Checker), the other is a legacy MFC project that uses a MultiByteCharacterSet encoding.

The legacy project has to use the library Project (to Spell check the contents of a richedit control interactively).

when I build a lone project with a richedit control, set the character encoding to unicode and reference the library, it works fine. but where I try to reference the library from the legacy project the same way I have done with the lone project, it doesn't work.

I investigated and realised that the TEXTRANGE structure that is being populated by the EM_GETTEXTRANGE expects a Unicode value in its lpstrtext member, which wouldn't be the case for the legacy project. the implementation in the library is as follows:

TEXTRANGE txtRange;
  memset (&txtRange, 0, sizeof(txtRange));
  memset (bufW, 0, sizeof (bufW));
  //debug_log("Size of TEXTRANGE: x: %d and Size of BufW: %d.", sizeof(txtRange), sizeof(bufW));
  txtRange.lpstrText  = string_from_unicode_cp(bufW, CP_ACP);
  txtRange.chrg.cpMin = 0;
  txtRange.chrg.cpMax = _countof(bufW);
  debug_log("count of bufw: %s.", bufW);
  SendMessage (hwnd, EM_GETTEXTRANGE, 0, (LPARAM)&txtRange);
  debug_log("txtRange.lpstrText is: %S",txtRange.lpstrText);

but I get the error:

SpellChecker.cpp(215): error C2440: '=' : cannot convert from 'char *' to 'LPWSTR'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

Visual Studio says that the lpstrtext member int he library is LPWSTR (perhaps because of the UNICODE format selected), which is understandable.

My question is, Is there a way to force lpstrtext member to expect LPSTR (cast) even when the project that contains it, is set to use unicode.


Solution

  • TEXTRANGE is a macro:

    #ifdef UNICODE
    #define TEXTRANGE   TEXTRANGEW
    #else
    #define TEXTRANGE   TEXTRANGEA
    #endif // UNICODE 
    

    So you should be able to use TEXTRANGEA instead to force char* type.