BSTR and Variant in C++

Author: Dave
Date: 03.27.16 - 4:23pm

to round out the last post on using a collection, I might as well cover how to pass a BSTR and a VARIANT to a C++ dll.

Variants are straight forward. Strings require some discussion.

Internally vb6 strings are BSTR type. Its a unicode string with a length prefix, that can contain embedded nulls (because the length is known).

Since the traditional winapi is all C dlls and expects either ascii or wide strings, the vb creators decided to do some magic when giving vb6 users access to the winapi through the declare mechanism. Since the api vb users use is the ascii api, these internal BSTRs are converted to ascii strings by the runtime before passing them to the winapi. If the string was declared as byval, then the temp buffer is also copied back to the vb BSTR before heading back to vb6 in case the api was filling in a buffer.

The vb6 declare mechanism wasnt really meant to handle automation types. If you want to accept a BSTR as an argument in your C dll, or use one as a return value, you cant do that by just declaring the argument (or retVal) as String.

One way to access a dll designed like this is to use a type library

module myDll
    BSTR DoStuff ([in] LPWSTR stuff);

The other way is to define the argument as long, and pass in the strptr(myString) to the api. StrPtr also comes with a will return 0 if the string has not yet been initialized. So you have to remember to set it to something first. To return a string from a traditional api would probably require copymemory without a typelib and isnt worth covering in my opinion.

Everything considered, just using a variant instead seems like the better way to go as you can use the api directly without strptr and its nuances.

Below is a quick example:

Private Declare Sub strTest Lib "teds.dll" (ByVal bstr As Long)
Private Declare Sub varTest Lib "teds.dll" (ByVal v As Long)
Private Declare Sub varTest2 Lib "teds.dll" Alias "varTest" (ByRef v As Variant)

Private Sub Form_Load()
    Dim b As String
    b = "can not be null" 'or strptr returns 0
    strTest StrPtr(b)
    MsgBox Len(b) & "  " & b
    Dim v As Variant
    'varTest VarPtr(v) 'this works
    varTest2 v         'this is easier..
    MsgBox Len(v) & "  " & v
End Sub


#pragma comment(lib, "comsuppw.lib")

#define EXPORT comment(linker, "/EXPORT:"__FUNCTION__"="__FUNCDNAME__)

void __stdcall strTest(BSTR buf)
#pragma EXPORT

	_bstr_t b; //used for auto conversion to olechar (wide)
	b = "This is my bstr!";
	SysReAllocString(&buf, b);


void __stdcall varTest(VARIANT *buf)
#pragma EXPORT

	_variant_t v;
	v.SetString("this is my test!");
	*buf = v.Detach();


If you want to test for memory leaks, you can add something like the following then watch the memory usage in the task manager.

Dim b() As Variant

Private Sub Command1_Click()
    Const sz = 1000000
    ReDim b(sz)
    For i = 0 To sz
        varTest2 b(i)
End Sub

Private Sub Command2_Click()
    Erase b
End Sub

The following also appears to work (with no mem leaks):

Private Declare Function retVar Lib "teds.dll" () As Variant
Dim v2 As Variant
v2 = retVar()
MsgBox v2

VARIANT __stdcall retVar()
#pragma EXPORT

	_variant_t v;
	v.SetString("this is my test!");
	return  v.Detach();


So i guess the moral of the story is, just ignore the string type in api declares if you want to use the BSTR. Leave the as string type it and its special handling for traditional C code which is was optimized for.

Ok had one more thought today while driving. You dont necessairly need to worry about string conversion at all for read only strings. If you compile your C to use wide char strings, you can just pass in the results form vb strptr()

Private Declare Sub wtest Lib "teds.dll" (ByVal wstr As Long)
wtest StrPtr("hello from vb!")
void __stdcall wtest(LPWSTR buf)
#pragma EXPORT

if you want to return binary data to vb6 as a string, you can do the following: (but it will probably cause problems on systems with extended char set languages such as chinese)

  Private Declare Function myMethod Lib "whatever"() As String
BSTR __stdcall myMethod()
     char binaryData[] = {0x80, 0x81, 0x00, 0xff};
     BSTR b = SysAllocStringByteLen((LPCSTR)binaryData,sizeof(binaryData));
     return b;

Comments: (0)

Leave Comment:
Email: (not shown)
Message: (Required)
Math Question: 34 + 27 = ? followed by the letter: J 

About Me
More Blogs
Main Site
Posts: (All)
2024 ( 2 )
2023 ( 9 )
2022 ( 4 )
2021 ( 2 )
2020 ( 4 )
2019 ( 5 )
2018 ( 6 )
2017 ( 6 )
2016 (22)
     VB6 CDECL
     UDT Tricks pt2
     Remote Data Extraction
     Collection Extender
     VB6 FindResource
     DirList Single Click
     Reset CheckPoint VPN Policy
     VB6 BSTR Oddities Explained
     SafeArrays in C
     BSTR and Variant in C++
     Property let optional args
     Misc Libs
     Enum Named Pipes
     Vb6 Collection in C++
     VB6 Overloaded Methods
     VB6 Syncronous Socket
     Simple IPC
     VB6 Auto Resize Form Elements
     Mach3 Automation
     Exit For in While
2015 ( 15 )
2014 ( 25 )
2013 ( 4 )
2012 ( 10 )
2011 ( 7 )
2010 ( 11 )
2009 ( 3 )