Writing C DLLs for use with VB


Author: David Zimmer
Site: http://sandsprite.com

Environment: VB6 + VC6 (originally). Updated 2026 with notes for current Visual Studio versions.

Updated 2026. This page was written in the VC6 days and has been corrected and extended. The biggest fix is in the strings section: a String passed ByRef through a Declare is also converted to ANSI, which the original text got wrong. When you outgrow this page, the VB6 and C interop notes go much deeper, and every rule there is checked by a test harness.

Writing C DLLs for use with VB


As your VB coding develops, one of the logical steps is to learn how to integrate C/C++ code with your VB projects.

There are a lot of reasons you might want to do this. C/C++ has tons of advanced code examples out there, and intrinsically has more built in power than VB.

This article is an introduction to writing C DLLs for use with VB. This file is not a definitive resource, I am writing this from what I know at the moment and what I have found through research, experimentation and debugging. There is actually a lot of stuff to know...way more than I can describe all inline here. So take this, and the code, as a rough guide to help you on your journey.

This article is half discussion, half tips and tricks. Its aim is to get experienced VB developers with some background in C up and running making standard C DLLs for use with VB. I have tried to put together as practical an example as I could and kept it as clear and direct as possible. This information has been put together through the knowledge gained across many books and many test projects.

If you are new to C and maybe even writing API declarations...it will take time to soak it all up, and you will have to search out other resources to help drive in the ideas. Relevant books that I recommend include

  • Jonathan Morrison's C++ for VB Programmers - excellent resource for VB developers looking to code in C
  • Bruce McKinney's Hardcore Visual Basic - on your VB6 MSDN CD in the Books section, and online at classicvb.net - old but good
  • Dan Appleman's Visual Basic Programmer's Guide to the Win32 API - good appendix on how VB calls DLLs
  • Matt Curland's Advanced Visual Basic 6 (PowerVB) - Advanced VB topics mostly COM related but also some standard DLL stuff
  • VB5DLL.TXT - Microsoft's notes on how VB calls C DLLs: strings, UDT alignment, arrays. Still the best single reference.
There are a lot of really poor books out there just waiting to empty your pockets. The ones above are professional level references that are worth keeping even after you have read them, as opposed to the textbook type books that you skim once and never open again.

Your first DLL in five minutes

Before the theory, here is the whole round trip at its smallest, so you have something that works to build on.

1. The C file, mylib.c:
#include <windows.h>

int __stdcall AddTwo(int a, int b)
{
    return a + b;
}
2. The export list, mylib.def:
LIBRARY mylib
EXPORTS
    AddTwo
3. Build it as a 32 bit DLL. VB6 is 32 bit only, so a 64 bit DLL will never load. From a "x86 Native Tools Command Prompt" (or after running vcvarsall.bat x86):
cl /nologo /W3 /O2 /MT /LD mylib.c /link /DEF:mylib.def /OUT:mylib.dll
In the Visual Studio IDE the same thing is a Dynamic-Link Library project with the platform set to Win32 (x86) and the .def file listed under Linker, Input, Module Definition File.

4. The VB side:
Private Declare Function AddTwo Lib "mylib.dll" (ByVal a As Long, ByVal b As Long) As Long
Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal f As String) As Long

Private Sub Form_Load()
    LoadLibrary App.Path & "\mylib.dll"     ' so the IDE finds it too, see below
    MsgBox AddTwo(2, 3)                    ' 5
End Sub
The two errors everyone hits first:
  • Error 53 "File not found: mylib.dll" - VB could not find the DLL. A compiled exe looks next to itself, but in the IDE "next to the exe" means the VB98 folder, so the DLL is not found unless you load it yourself first by full path (the LoadLibrary line above). Error 53 also shows up when a DLL that your DLL needs is missing, for example the VC++ runtime when you built with /MD instead of /MT.
  • Error 453 "Can't find DLL entry point" - the name is not exported the way VB asks for it. Check the .def file and the spelling (names are case sensitive), or run dumpbin /exports mylib.dll to see the real names.
Now the theory behind each piece.

Standard DLLs vs ActiveX DLLs

First let me introduce you to some Visual C terminology. There are several ways to create a DLL using Visual C++. In VB, all of the DLLs we create are ActiveX DLLs, which means they are actually COM servers housed in a DLL file.

You can make ActiveX DLLs in VC, however we are going to take a more basic approach and write a traditional standard call DLL so we don't have to worry about the overhead and complexity of ATL and complex raw COM types.

In VB we are used to interacting with these traditional DLLs in the form of the Windows APIs. Traditional DLLs require the use of manually entered Declare statements to use them in VB.

Calling conventions

To start off, C defines several possible function calling conventions. The calling convention describes in what order arguments are pushed onto the stack and who is responsible for cleaning up the stack when the function returns.

For our C-VB interactions we must use the standard calling convention (__stdcall) because this is what VB expects. If you forget to include this, you will get an error "Bad DLL Calling Convention" (error 49) in the IDE when you try to run your code. Be careful: a compiled exe does not check, and a cdecl function can even appear to work there until the stack runs out (every call leaves its arguments behind), so always try a new DLL in the IDE as well.

Data types

The next thing we need to know is how to map our commonly used VB types into something we can deal with in C. Because of C's power and flexibility, there are actually multiple ways we can deal with our VB data types. The most basic types are those that have a direct C counterpart:
  • VB Byte is one byte and maps to C unsigned char (VB has no signed byte).
  • VB Integer is 2 bytes and maps to C short. It is not the C int.
  • VB Long is 4 bytes and maps to C int or long (and to handles and pointers).
  • VB Boolean is a 2 byte VARIANT_BOOL where True is -1. A Win32 BOOL is a 4 byte int, so declare it As Long, and a C/C++ bool is a single byte, so declare it As Byte. Getting this wrong compiles fine and then gives True where you expected False.
The full table is on the Using C Dlls page.

When you look at an API declaration you may have noticed that some of the arguments are passed ByRef and some are passed ByVal. (If the API Declaration does not define either, it is ByRef by default.) So what does this mean to our C function?

Just like with VB functions, a ByRef argument means to pass in the actual variable used in the calling code. This is done by passing in a pointer to the original variable. (A pointer is just the numeric address in memory of the original variable.) A ByVal argument type means to push a copy of the variable's value onto the stack for the called function to use.

Let's see an example.
VB Declare   : ...(ByRef val1 As Long, ByVal val2 As Long)
C prototype  : ...(int* val1, int val2)
It is very important you understand the difference between the two. When you get to be writing Declare statements for your own DLLs, the ByVal, ByRef mixups are going to cost you many crashes until you get the feel for it.

If you got something wrong and are running in the IDE, the entire IDE will crash and you could lose your work. Always set VB to save changes every time you run from the IDE (Tools, Options, Environment, "When a program starts: Save Changes") to help prevent lost work. Common error messages include "Bad DLL Calling Convention", "Can't find DLL entry point", and memory read/write exceptions caused by trying to reference memory at some low address.

If your code works fine, but then crashes when the function is ready to return back to VB, you could have either used the wrong calling convention (stack not cleaned up) or the argument list in the Declare does not match the C function (a missing argument, or a ByRef where C expects a value).

We will get into some general debugging hints later on.

Strings

Next we are going to look at the VB String type, for which we (again) need a little more background.

VB is based around COM and uses COM types for its variables. The VB String we all know and love is actually a BSTR type to C. A BSTR is a Unicode string with a length prefix. This length prefix allows the string to contain embedded nulls and makes it very easy to read the length of a string (the VB Len() function uses this).

Standard C coding usually uses char arrays (byte arrays) to hold its strings. These strings are typically held in a fixed size array and terminated with a null character ( Chr(0) ).

Here is the important part. A Declare was designed to call the ANSI Windows API, so whenever a String goes through a Declare, ByVal or ByRef, the VB runtime makes a temporary ANSI copy of it, passes that to C, and copies it back into your Unicode string when the call returns:
  • ByVal s As String - C receives a char* to the ANSI copy. If the buffer is big enough, C can change its contents and the change comes back to VB. You cannot write past the end of it, or you will corrupt other memory and most likely crash.
  • ByRef s As String - C receives a BSTR*, a pointer to that same ANSI copy. It looks like a native BSTR, but its contents are one byte per character. Because C has the pointer to it, C can free it and put a new string of any length in its place. Use SysAllocStringByteLen for that (it takes ANSI bytes), not SysAllocString or SysReAllocString, which expect wide characters.
// C - change the length of a string passed ByRef
void __stdcall SetString(BSTR* pbs)
{
    const char* s = "a new value of any length";
    SysFreeString(*pbs);
    *pbs = SysAllocStringByteLen(s, (UINT)lstrlenA(s));
}

' VB
Private Declare Sub SetString Lib "mylib.dll" (s As String)
A few things follow from this:
  • Characters outside your system code page do not survive the trip.
  • When C fills a buffer, tell it the size with Len(s), not LenB(s). C sees the ANSI copy, one byte per character, and LenB would claim the buffer is twice as big as it really is.
  • A C function that returns a String through a Declare must return ANSI bytes in a BSTR (SysAllocStringByteLen). The runtime converts it to Unicode for you.
  • If you want the real Unicode string with no conversion, pass StrPtr(s) declared ByVal As Long (C gets a read only wchar_t*), or pass the string inside a Variant (C gets a VARIANT* holding the real BSTR). Both are covered in the interop notes.

Arrays

The next common area people wonder about is how to pass and access arrays.

There are two common ways to do this. One uses pointer arithmetic and the other uses the standard VB array type, which is a SAFEARRAY as C knows it. The SAFEARRAY structure (a Type, as VB developers know it) is defined in oleauto.h.

First we will describe the pointer arithmetic method.

Array elements are laid out sequentially in memory and take up a known number of bytes based on their type. An array of Longs will be a block of memory where every 4 bytes defines one element.

If we pass the first element of our VB array ByRef, we are actually passing in the address of the beginning of that array. If we also include how many elements are in the array as a function argument, we can now loop through all the sequential memory locations to get the corresponding values. Remember the count is UBound(a) - LBound(a) + 1. Passing just UBound(a) silently drops the last element.

See the code for an example of this. A word of caution: pointer arithmetic in C goes by the size of the type of pointer you are using. An int pointer will step 4 bytes of memory for each element accessed, a char one byte, so make sure you use the right type of pointer to correspond to the VB type you pass in. Do not work with BSTR strings in this way.

The next way to work with arrays between VB and C is to use the native VB array object, the SAFEARRAY mentioned above. Declare the argument as arr() As Long and C receives a SAFEARRAY**. See the example code for usage. With this method you do not need to pass in the number of array elements because it is contained in the SAFEARRAY structure. Check it is not NULL first: a dynamic array that was never ReDim'd arrives as a NULL pointer.

Variants

The next thing you may want to work with is Variant data. The VB Variant type is a handy thing, it can contain data of any type and you can change it on the fly...but how is that data really held behind the scenes and how can we access it in C? The VARIANT data structure is actually a large union with a field defined for each different possible data type. A type descriptor field precedes the union and is used as a flag to mark what type of data the VARIANT union currently contains. To use a VARIANT you receive as an argument, first test its .vt member for the variable type, then you can access the specific field in the structure for that type to get the actual variable data. If you write a new value into a VARIANT that VB passed you, call VariantClear on it first so its old contents are freed.

Callbacks

The last commonly sought after example I have included is how to perform a callback to a VB function from your C DLL by using a function pointer you supplied in VB. In C you can define function pointer variables that will let you call a function just by having its address. VB has no such native support, but the AddressOf operator gives you the address of a VB function to hand to C.

First make sure to declare your function pointer prototype as __stdcall. Second, in VB your callback function has to be in a module. To get the address of a function in VB, you need to use the AddressOf operator, which only works for functions contained in modules. Why? Because forms and classes are instances that could go away. Module functions are guaranteed to exist and not change for the life of the application. Two more rules: only call back from the same thread VB called you on (the VB runtime is not set up on other threads), and put an error handler in the callback, since a VB error cannot travel back through your C code.

If you need a callback into a class, the clean way is not the vtable hack: pass ObjPtr of the object to C and have C call a public method on it by name through IDispatch. The interop notes have an example.

The .def file

One other aspect of compiling a C DLL for use with VB I should mention is the use of a .def file. The .def file is a simple plain text file that lists the exact function names you want used in the export table of your DLL. If you do not include it, the compiler will decorate your function names to include other bits of info (_AddTwo@8, or something much longer in C++). Use the .def file to prevent this. (The other way is a #pragma comment(linker, "/EXPORT:...") line inside each function, also shown in the interop notes.)

Remember, every time you add a new function to your C DLL, you are going to have to add its function name to the list of exports in the .def file, as well as write a new Declare statement to include in your VB app.

If you get error 453 "Can't find DLL entry point" when trying to run your VB app, then there is a good chance you forgot to add the new function name to the .def file exports list.

Lastly, it's worth noting that there are multiple ways to pass stuff. Here are some other alternatives for char pointers:
void __stdcall test(char* x)

Declare Sub test1 Lib "x.dll" Alias "test" (x As Byte)            ' pass b(0): a byte buffer
Declare Sub test2 Lib "x.dll" Alias "test" (ByVal x As String)    ' an ANSI copy of the string
Declare Sub test3 Lib "x.dll" Alias "test" (ByVal x As Long)      ' any address you like

Dim b(50) As Byte
Dim s As String

s = Space(50)
test1 b(0)
test2 s
test3 VarPtr(b(0))

Building with a current Visual Studio

  • Any recent Visual Studio with the "Desktop development with C++" workload works. Always build for Win32 / x86.
  • Build with the static runtime (/MT, under C/C++, Code Generation, Runtime Library) so your DLL does not need the VC++ redistributable on the user's machine.
  • While the VB6 IDE has your DLL loaded it keeps it open until the IDE closes, so the linker cannot overwrite it ("cannot open file mylib.dll"). Test through your compiled exe, or close the IDE before rebuilding.
  • On Vista and later, the VB6 IDE should be set to run in Windows XP compatibility mode, which in practice means starting it as administrator.

Debugging tips and tricks

  1. Compile your VB exe with debugging info: Project, Properties, Compile tab, "Create Symbolic Debug Info".
  2. Compile your C DLL in the Debug configuration.
  3. You can call the debugger from VB code by using the DebugBreak API (then press F10 twice to step to your code), or put __debugbreak(); in the C code.
If you compiled your VB exe with debug info, you will be able to see your VB source interspersed with the actual assembly that is running. Together with the other Visual Studio debugger tools this is a very powerful way to see what is going on!

If you compiled your DLL in Debug, then you can set breakpoints in your C code and have it drop you into the debugger when it gets called.

To get to a breakpoint in your DLL, compile a copy of your VB project into the same folder as the debug DLL. In your DLL project's properties set Debugging, Command to that exe (or to VB6.EXE if you want to debug while running in the VB IDE), then press F5. Visual Studio starts it, and your breakpoints are hit when VB calls the DLL. You can also attach to an already running process with Debug, Attach to Process. When you are at a breakpoint like this, you will have very nice debug tools at your fingertips that are way beyond what the VB debugger has.

Learn to use the Visual Studio debugger well. If you really want to expand your skills to that next level, it will soon become your new best friend.

If you get errors on startup that you cannot set breakpoints and some have been removed, it is probably because you are compiling in release mode without debug info. You really do not want to try to debug looking only at asm.

Downloads

  • Download demo project & Source - 70 KB. Strings ByVal and ByRef, filling buffers, returning a BSTR, arrays by pointer and as SAFEARRAYs, Variants, an AddressOf callback, returning a struct, and inline asm.
Note on the demo: two of its string functions (AlterString and ReturnBstr) call SysReAllocString/SysAllocString with a plain char*. That compiles in C and usually seems to work, but those functions expect wide characters. Use SysAllocStringByteLen as shown in the Strings section above. Also, the array demo passes UBound(tmp) as the element count, which skips the last element.
Other Integration Examples:

Where to go next

  • VB6 and C interop notes - everything on this page in more depth: Unicode strings, returning arrays, structs, objects, a list of runtime errors and what they mean, and patterns from large projects (script engines, debuggers, talking to other processes).
  • Using C Dlls - the VB to C type table and more reading.
  • Linking C obj files into VB - put the C code inside your exe instead of shipping a DLL.
  • AI Assisted VB6 Development - its vbai_compile_help package includes a C DLL and VB6 test harness that checks every rule above.