Originally Posted by
MSDN
... Functions should return types that VBA can recognize ByVal. This means that some types are more easily returned by modifying arguments in place: strings, arrays, user-defined types, and objects.
...
To return a byte string to VBA from a DLL, you should modify a byte-string BSTR argument in place. For this to work, you must declare the DLL function as taking a pointer to a pointer to the BSTR and in your C/C++ code, and declare the argument in the VBA code as ‘ByRef varg As String’.
You should only handle strings that are passed in these ways from VBA using the OLE BSTR string functions to avoid memory-related problems.
So MSDN prefers that you return string by reference. But I see plenty of examples returning BSTR's to VB[A] (like this:Financial applications using Excel ... - Google Books)
I may of incorrectly assumed that the given BSTR will be null-terminated. Try out these functions and see what you get:
Code:
BSTR WINAPI string_test1()
{
const char *s = "Testing 123";
return SysAllocStringByteLen(s, strlen(s));
}
BSTR WINAPI string_test2(BSTR stringVar)
{
const size_t len = SysStringByteLen(stringVar);
const char *begin = (const char*)stringVar;
const char *end = begin + len;
std::string buffer(begin, end);
return SysAllocStringByteLen(buffer.c_str(), len);
}
gg