unicode beaten by memcopy?
I am using CALLBACKS to communicate between a VB App and an app Written with VC6.0.
Here is the problem: When the (English) App was written, it was not coded using unicode.
Well the obvious solution would be to set _UNICODE and go about my life. Well this
would also cause about 3E09 errors and I would have to sack a small village to get
the budget or the time to do this. :)
This works, but what I want to know is why!
Why does memcopy copy the data from the BSTR into ProcLine, which is a TCHAR correctly?
BSTR = *OLECHAR = *WCHAR
#ifdef _UNICODE
TCHAR is a WCHAR
#elif defined (_MCBS)
TCHAR is a char
#YADA YADA
//shared data
TCHAR ProcLine[256];
///...later in the DLL
int _declspec (dllexport) CALLBACK PutProcLine(BSTR line)
{
memset(ProcLine,0,sizeof(ProcLine));
memcpy(ProcLine,line,sizeof(ProcLine));
procdtevent.Lock();
return 0;//success
}
int _declspec (dllexport) CALLBACK GetProcLine(BSTR *line)
{
_bstr_t tmp = *line;
TCHAR tline[288];
_stprintf(tline,"%s",ProcLine);
_bstr_t ret = tline;
*line = ret;
procdtevent.SetEvent();
return 0;
}
I mean ProcLine would be riddled with NULLs unless memcopy castes each short in the
BSTR to byte and life is ok because of little endian.
[1386 byte] By [
ahoodin] at [2007-11-19 19:43:56]

# 1 Re: unicode beaten by memcopy?
'memcpy' does no casting. It does a bit-bit copy, IIRC. I'm betting that this works because in the UNICODE version, 'sizeof(ProcLine)' is a different size then in the non-UNICODE version. In other words, because the code uses the 'sizeof' function (?) instead of a fixed number, this works for both UNICODE and non-UNICODE builds.
Viggy
# 2 Re: unicode beaten by memcopy?
memcpy(ProcLine,line,sizeof(ProcLine)); Why are you copying sizeof (ProcLine) number of bytes from a BSTR called line to a TCHAR* called ProcLine?
There is no guarantee that the code *will* work reliably and always.
Reason being the cases when the BSTR called line is smaller in length than sizeof (ProcLine) / sizeof (TCHAR), you are actually reading the BSTR beyond it bounds - i.e. you are overrunning the buffer allocated to line. In these cases, you are actually copying a smaller string object (and beyond) into a larger one - and so long as the copy works (i.e. by stroke of luck the buffer overrun doesn't crash), ProcLine will contain the right data. However, this is working by stroke of luck and nothing more.
For cases when the length of the BSTR line is greater than sizeof (ProcLine) / sizeof (TCHAR), ProcLine will contain an incomplete string as number of bytes being copied are less than those contained in the source.
Bottomline is - what you see as working... Is working by stroke of luck. ;)