Hi All,
After searching for info, I came out with two functions to come and go from BSTR to std::string and vice versa...
The functions work fine for me and I can call them directly from a Cell in Excel, operate then inside the DLL and return the result as BSTR to Excel; Excel will correctly interpret the received string.
This is how I declare the function under VBA:
Code:
Declare Function string_test Lib _
"d:\datos\doc\tech\c++\excel\ipfnc_dll\ipfnc.dll" _
(ByVal mystring As String) As String
This is my function within C++ to convert from BSTR to std::string:
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);
return buffer;
}
}
And this is the one to convert from std::string to BSTR:
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);
// 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.
return SysAllocString(buffer);
}
Any improvement is welcome ... but so far they are working ...
Regards,
Lucas
ps: Actually, the function BSTR string2bstr(string input_string) was given to my by tabstop (thanks for this!).