Return a
BSTR
string from C++ function. VB string is actually VC++
BSTR
underneath. Call
SysAllocString()
to allocate a
BSTR
string.
SysAllocString()
takes in Unicode string as input. You need to convert your ASCII
char*
string to unicode
wchar_t*
. You need not free the
BSTR
, VB6 will free it for you with
SysFreeString()
.
Before using
SysAllocString()
, you have to include
OleAuto.h
header file and the import library,
OleAut32.lib
.
#include <OleAuto.h>
#pragma comment(lib, "OleAut32")
extern "C"
{
VBDLLFUNC(BSTR) MDNSgetPath()
{
BSTR result = ::SysAllocString(L"Some text");
return result;
}
}
Below is a naive function to convert ASCII to Unicode string type.
#include <string>
std::wstring ToWideString(const std::string& src)
{
std::wstring result = L"";
for(size_t i=0; i<src.size(); ++i)
{
result += (wchar_t)src[i];
}
return result;
}
Your new
MDNSgetPath()
will call the
ToWideString()
which in turn calls your
getPath()
.
extern "C"
{
VBDLLFUNC(BSTR) MDNSgetPath()
{
BSTR result = ::SysAllocString(ToWideString(getPath()).c_str());
return result;
}
}
The final
MDNSgetPath()
can be simplified into 1 line by removing the temporary
result
variable.
#include <OleAuto.h>
#pragma comment(lib, "OleAut32")
extern "C"
{
VBDLLFUNC(BSTR) MDNSgetPath()
{
return ::SysAllocString(ToWideString(getPath()).c_str());
}
}