Link to home
Start Free TrialLog in
Avatar of dwinkler
dwinkler

asked on

Converting a unicode string to a mbcs (multi byte character) string

Ok I am having no luck on a Japanese machine using the following code to convert a unicode string to a mbcs :

size_t nSize = wcstombs( NULL, pszWide, NULL );

if( nSize != (size_t)-1 )
{
  m_pszShort = new char[nSize+1];

  m_pszShort[nSize] = '\0';

  size_t nCopied = wcstombs( m_pszShort, pszWide, nSize );
}

When I try to convert a legitimate Unicode character under the OS locale, it always returns -1.  I've
am absolutely positive that the single unicode japanese character in the pszWide string is valid (if
I save the text file as html it replaces it with the decimal equiv, which I verified is the value in
pszWide).

Is the wcstombs function broke?  Or is there something I am missing?
ASKER CERTIFIED SOLUTION
Avatar of snoopym
snoopym

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dwinkler
dwinkler

ASKER

Figured it out (kind of).  Points go to the person who can answer the new questions.  You must call setlocale(...) in each exe and dll.  Does anyone know why?  Shouldn't the dll and exe be in the same address space with the same global variables?  So you can either place the setlocale in either a function of the dll that is called or in a callback from the exe:

i.e. if you want to call sprintf( mbcsbuf, "%ls", widebuf ); inside of the dll and get the correct result.

A - application
B - dll

A->setlocale( LC_ALL, "" ); (does not work)

A->B->setlocale( LC_ALL, "" ); (works)

A->B->A->setlocale( LC_ALL, "" ); (works)

How does it switch context between the dll globals and the exes?
First of all, wcstombs is a C runtime library function. It is therefore limited by the same rules as the RTL. Therefore, if you have an application and a DLL and you want them to act as if they were compiled together, then you need to make sure that both the EXE and the DLL were compiled with the same compiler with the same compiler options AND you need to make sure they were built the SHARED version of the RTL. See the online help with /MD (if you are using Visual C++).

No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
 - PAQ'd and pts removed
Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

Nic;o)