Ok, so here are the functions freeing (and deleting) the memory used:
string2bstr:
Code:
BSTR string2bstr(string input_string)
{
// MultyBytetoWideChar converts ANSI strings to UNICODE
// int len2 is the required size in wide chars
// it includes the NULL char at the end. So it's "len"+1
// The codepage CP_ACP -AnsiCodePage- is used by Windows (Excel)
// When using 'As string' in VBA causes autmatically UNICODE->ANSI conversion.
int len2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, input_string.c_str(),-1, NULL, 0);
// malloc returns a pointer to the begining of the buffer
// buffer size in memory is (len2*sizeof(*buffer))
// 5th parameter of MultiByteToWideChar is LPWSTR
// 1st parameter= CP_ACP = ANSI Code Page
LPWSTR buffer = (LPWSTR)malloc(len2 * sizeof(*buffer));
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, input_string.c_str(), -1, buffer,len2);
// SysAllocString allocates a new string and copies the passed string into it.
// The input_parameter must be a Unicode string in 32-bit applications,
// and an ANSI string in 16-bit applications. The input parameter may be NULL.
BSTR out_buffer;
out_buffer = SysAllocString(buffer);
// since we allocated memory to accomodate the string
// --(LPWSTR)malloc(len2 * sizeof(*buffer)))--
// we must then delete it. To do so, we created BSTR out_buffer and
// copied into it the information within 'buffer'.
free(buffer);
return out_buffer;
}
bstr2string:
Code:
string bstr2string(BSTR input_string)
{
DWORD len, bstrLength;
size_t result;
// +1 for NULL teminator
// bstrLength is measured in Chars
bstrLength = SysStringLen(input_string)+1;
// len is measured in Bytes
len = WideCharToMultiByte(CP_ACP, 0, input_string, bstrLength, 0, 0, 0, 0);
if (len>0)
{
char *buffer = new char[len];
result = WideCharToMultiByte(CP_ACP, 0, input_string, bstrLength,buffer,len, 0, 0);
// since we allocated memory to accomodate the string --new char[len])--
// we must then delete it. To do so, we create std::string out_buffer and
// copy into it the information within 'buffer'.
string out_buffer = buffer;
delete buffer;
return out_buffer;
}
else
{
return ("Error");
}
}
@Codeplug:
I'll study your code (I need to deepen my knowledge regarding C++ data types in order to fully understand the difference between std::string and std::wstring before moving on). After that I'll promise I'll try to improve my functions with your suggestions ...
Thanks to everyone ... again, any improvement is very welcome ...
Rgds!
Lucas