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: 5 + 58 = ? followed by the letter: H 

About Me
More Blogs
Main Site
VB6 Console Apps
VB6 Debugger View As Hex tooltips
VB6 - C Share registry data
VB6 Addin Missing Menus
VB6 Class Init Params
VB6 isIn function
Python and VB6
Python pros and cons
download web Dir
vc rand in python
VB6 Language Enhancement
Register .NET as COM
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
C# self register ocx
VB6 Class Method Pointers
JS Debugger
Duktape Debug Protocol
QtScript 4 VB
Vb6 Named Args
vb6 Addin Part 2
VB6 Addin vrs Toolbars
OpenFile Dialog MultiSelect
Duktape Example
DukTape JS
VB6 Unsigned
.Net version
TitleBar Height
.NET again
VB6 Self Register OCXs
Query Last 12 Mos
Progid from Interface ID
VB6 to C Array Examples
Human Readable Variant Type
ScriptBasic COM Integration
CodeView Addin
ScriptBasic - Part 2
Script Env
printf override
History Combo
Disable IE
API Hooking in VB6
Addin Hook Events
FastBuild Addin
VB6 MemoryWindow
Link C Obj Files into VB6
Vb6 Standard Dlls
CStr for Pascal
Lazarus Review
asprintf for VS
VB6 GlobalMultiUse
Scintilla in VB6
Dynamic Highlight
WinVerifyTrust, CryptMsgGetParam VB6
MS GLEE Graphing
printf for VB6
C# App Config
Tero DES C# Test
VC 2008 Bit Fields
Speed trap
C# Db Class Generator
VB6 vrs .NET (again)
FireFox Whois Extension
git and vb6
Code Additions
Compiled date to string
C# ListView Sorter
VB6 Wish List
C# Process Injection
C# PE Offset Calculator
VB6 Async Download
Show Desktop
coding philosophy
Code release
Dll Not Found in IDE
Advanced MSScript Control
random tip
Clipart / Vector Art
VB6 Callback from C#
Binary data from VB6 to C#
CSharp and MsScriptControl
HexDumper functions
Js Beautify From VB6 or C#
vb6 FormPos
Inline Asm w VB6
The .NET Fiasco
One rub on computers
Universal extractor