Here's a smple.
In C++
extern "C" void WINAPI TEST(BSTR* bstr)
{
DWORD len, bstrLength;
// +1 for NULL teminator
bstrLength = SysStringLen(*bstr)+1;
len = WideCharToMultiByte(CP_ACP, 0, *bstr, bstrLength, 0, 0, 0,
0);
size_t result;
if(len > 0)
{
char* buffer = new char[len];
result = WideCharToMultiByte(CP_ACP, 0, *bstr, bstrLength,
buffer,len, 0, 0);
MessageBoxA(NULL, buffer , "MultiByte",0);
delete buffer;
}
};
In VBA
Private Declare Sub TEST Lib "C:\BSTRTEST.dll" (ByVal strIn As Long)
Sub TESTPROC()
Dim s As String
s = "abc"
TEST VarPtr(s)
End Sub
To pass a UNCODE string from C++ to VBA
In VC
extern "C" void WINAPI TEST1(BSTR* strIn, BSTR* strOut)
{
//in: UNICODE , out: UNCODE
wchar_t* conststr = L"abc";
BSTR rt = SysAllocStringLen(NULL, SysStringLen(*strIn) + 3);
wcscat(rt,conststr);
wcscat(rt,*strIn);
if(*strOut !=NULL)
{
SysFreeString(*strOut);
}
*strOut = rt;
};
In VBA
Private Declare Sub TEST1 Lib "C:\BSTRTEST.dll" (ByVal s As Long,
ByVal s2 As Long)
Sub main()
Dim s1 As String
s1 = "aaa"
Dim s2 As String
TEST1 VarPtr(s1), VarPtr(s2)
Debug.Print s2
End Sub
By the way, the problem b) I wrote in the previous post is wrong.
The truth may be , you cannot pass the char* which is allocated in c++
from c++ to VB, since nobody can delete the allocated space and causes
memory leak.
|