The University of Birmingham Visual Basic & Visual C++ tips Engineering at Birmingham
School of Engineering > EECE > Tim Collins > Visual Basic & Visual C++ tips

Creating a DLL in Visual C for use with Visual Basic

For a lot of Windows based signal processing applications, the choice of programming language isn't obvious. C (or even assembler) might be preferred to do the number crunching whilst a higher level language like Visual Basic for the GUI. A solution in these situations is to call C functions from Visual Basic by compiling them in a DLL. The manuals and help file don't make this easy to follow, but when you've done it once it really is quite straightforward.

In Visual C :

1. Start a new DLL project:

File | New | Project - “Win-32 Dynamic Link Library”

(give the project a name, projname, and click OK)

2. Add a source file

File | New | Files - “Text File”

Which will be the source code, filename.c

Either tick the “Add to Project” box or remember to add it later.

3. Write the functions

For each function in filename.c that you want to call in Visual Basic from the file projname.dll, declare the function as:

__declspec(dllexport) void __stdcall funcname(argument list)

NB. Note these are double underscores (‘__’ not ‘_’)

Write the code for the function as usual, save it and build projname.dll.

In Visual Basic :

1. Create the project

Create a new project or open an existing one. Create your windows etc. as usual.

2. Add the DLL declaration(s)

Add a new module and type the line :

Public Declare Sub procname Lib “projname.dll” Alias “decoratedname” (ByRef x As Long)

Obviously the arguments should reflect the original argument list, e.g. “int *x” becomes “ByRef x As Long”, “char y” becomes “ByVal y As Byte” etc.

decorated name = _funcname@N

where N=total number of bytes that are required for argument list (e.g. 2 for a short, 4 for any 'ByRef' pointer, 8 for a double etc.).

Now, procname can be used as if it were a normal Visual Basic procedure. If you want to return a value, the declaration should be changed to a "Function" rather than a "Sub" and a return() included in the C function. Also, the return type must be added on the end of the VB declaration as usual.

NB. To pass an array to the function, pass the first element by reference

Example

In C :

__declspec(dllexport) void __stdcall loadimage(unsigned char *x)

In Basic :

Public Declare Sub loadimage Lib “projname.dll” Alias “_loadimage@4” (ByRef x As Byte)

Dim x(10) As Byte

loadimage x(0)

Tim Collins, 18/6/99.