Click here to Skip to main content
15,867,453 members
Articles / Web Development / HTML

DllExports - Common Problems and Solutions

Rate me:
Please Sign up or sign in to vote.
4.87/5 (73 votes)
8 Aug 2014Ms-PL8 min read 97.9K   1.8K   135   41
Learn how to export functions from a DLL, and obtain full language independence

Screenshot of DemoAppNative.exe

Introduction

There are numerous guides on how to export functions from DLLs, but somehow when you start doing DLLs yourself, you run into problems. If you create a DLL in one language and want to use it from another, there are some pitfalls to be aware of. We will look at some of them.

The key to solving problems is really understanding what is going on. I am going to naively start with a simple C++ DLL, and try to lead us into some of the most common problems, Then we will make modifications to the DLL to remedy the problems.

Background

Sooner or later, you will find the need to use a DLL with exported functions. Either using a third party library or exposing a public API yourself to a third party.

Let's go back a few years. Back to where VB6 was popular. VB6 was a fantastic language for doing rapid prototyping in. You would learn how to work with GUI code in just a couple of days. VB6 was initially compiled into Pcode, which was interpreted at runtime. Later on, the possibility to compile this code into an EXE was added.

VB6 was quite slow, and lacked elementary things like unsigned integers and bit shifting, and I think without being able to use DLLs made in other languages, VB6 would never have had as much success as it did.

When speed really was needed someone just made a DLL in C or C++, or in any other language. Creating GUI in VB6 was a pleasure compared to doing it with GDI or MFC. You could have the best of both worlds.

How could VB6 call C++ DLLs? Well. Let's consider an assembly example where we add 2 numbers, stored in registers AX and BX.

C++
int Add(int a, int b)
{
__asm
  {
    ADD AX, BX     // AX = AX + BX
    RET
  }
}

To call this from VB6 any other language. The only thing we need to do is jump to the code location and set AX and BX. The way parameters are passed to a function is called "Calling convention". Some conventions pass parameters via the stack, others through registers, or a combination of both. VB6 uses a calling convention called __stdcall. It is also the standard win32 convention. Parameters are pushed on the stack from right to left, the return value is stored in AX, and the function is responsible for balancing the stack. C and C++ compilers uses by default __cdecl calling convention, which is similar to __stdcall, but the caller of the function is responsible for balancing the stack. In order to make VB6 able to call exported function, we need to change the calling convention to __stdcall.

I use VB6 as example here, but I would recommend to always use the __stdcall convention in order to be more language independent, and conform to the operating systems convention.

Creating a DLL Project with a Minimal Stub

This article is primarily about managing the exported names and ordinals. I will be very brief, and just quickly show how the demo DLLs were created.

Select a new C++ win32 Console Application:

Selecting a console project

Set the type to "DLL":

Changing type to DLL

DLLMain

Not only programs have a Main function, but also DLLs. Here, you typically allocate and initialize resources and free resources. The one below is autogenerated, and I did no modifications to it.

C++
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

__declspec(export)

There is very little you need to do to export a function. You only need to decorate it with __declspec(dllexport). I will combine it with the __stdcall attribute, to change the calling convention.

C++
__declspec(dllexport) int __stdcall Add(int a, int b)
{
  return a + b;
}

When you compile, a DLL and a .lib file will be created. If you want the DLL to be automatically loaded into your application at run-time, you need to add the .lib file when you link your application.

From an application, you need to add a reference to the .lib file either in the project settings or programmatically via a pragma link directive. I personally prefer the pragma directive, because project settings are per build configuration, and you have to remember to update all configurations.

C++
#include "../DemoLib1/DemoLib1.h" //  __declspec(dllimport) int __stdcall Add(int a, int b);

#ifdef _DEBUG
#pragma comment(lib, "../Debug/SimpleMath.lib")
#else
#pragma comment(lib, "../Release/SimpleMath.lib")
#endif

int main()
{
  int result = Add(1,2);
}

This is the most basic form of function export/import via a DLL, but I wouldn't qualify it as a good DLL. This DLL has very poor interoperability with other compilers and languages.

One Step Towards Interoperability

If our intention was to use the DLL from C, Pascal, VB6, C# or some other language we will be dissappointed. This DLL is only useable from C++.

Let's use bindump.exe, a tool part of the Windows SDK and Visual Studio, to see why other languages don't like the DLL.

C++
bindump.exe /EXPORTS 

Output from dumpbin on DemoLib1.dll

The name Foo is C++ mangled. Type information has been encoded into the function name by the C++ linker. This is ok, as long as your application also is written in C++ and you compile it with the same compiler and linker. The C language does not mangle the names the same way C++ does.

Remember the extern "C" keyword for making C/C++ interoperate.

C++
extern "C"
{
  __declspec(dllexport) int __stdcall Foo(int a, int b);
}

Now the exported names are not C++ mangled anymore.

Output from dumpbin on DemoLib2.dll

Now the name is "_Foo@8". Why is the name _Foo@8 instead of just Foo? Well, now it is C language mangled. C decorates its functions with a leading underscore, followed by the name of the function, and it ends the name with the size in bytes of the parameters. We are passing 2 integers (4 bytes). So the total size is 8. You can now use the DLL from both C and C++, instead of just C++ in the previous example. This is an improvement, but still it is not generic enough.

The calling convention is strictly specified, but the decorated name is more loosely specified. There are languages that don't decorate the name at all. We might be able to call this method using the decorated name instead, by running dumpbin.exe on the DLL and lookup the decorated name, but that name may change if you change compiler, or add/modify any of the parameters. This is a huge drawback.

If you look closely, the mangled name "_Foo@8" is repeated twice. _Foo@8 = @ILT+235(_Foo@8) The one of the left is the exported name, and the one on the right is the internal name. At this moment, they are the same. In the next section, we will learn how to change the exported name.

One Step Back, Two Steps Forward - Use a .def File

.def files gives you more control of how functions are exported. I don't know how some people writing guides on DLLs fail to mention them. I always add one.

Add a file preferably ending with .def to your project. The name doesn't matter. I named my file exports.def, because that is what I always do.

Adding a .def file to the project

The export file should have the following format:

C++
LIBRARY DemoLib3
EXPORTS
   Foo   @1

Go into the property page for the project, and add it under "linker input".

Updating project linker settings to use the .def file

Adding this file will "unmangle/undecorate" the exported function name.

Output from dumpbin where function name is not decorated

What More Can a .def File Do

Functions that are exported from a DLL are assigned a number and optionally a name. For public functions, it makes sense to add a name. For internal functions that are not intended for public use, you can assign them a number, but leave out the name. Let's have a look at the exports from USER32.dll.

Mangeled names

There are 1062 exported functions, but only 894 named functions. That means that you can only access them by Ordinal. The Ordinal is usually a number starting from 1. But it may optionally start from a different number, like 1502.

Let's create a DLL ourselves. One that exports two functions. The public function Foo, which is exported by name and ordinal. We will also add a private function Foo, that can only be accessed by ordinal. To make it more interesting, we will make the ordinals start at 1502, and we will have a hole in the number series, and give Bar the ordinal 1505.

In order to hide the name, we will use the NONAME directive.

C++
LIBRARY DemoLib4
  EXPORTS
     Foo   @1502
     Bar   @1505  NONAME

Mangeled names

In order to access it, you may write:

C++
HMODULE hLoadedLibrary = LoadLibrary("DemoLib4.dll");

// Notice __stdcall on function pointer typedef
typedef int (__stdcall* BarFunc)(int, int); 
   
BarFunc Bar = (BarFunc) GetProcAddress(hLoadedLibrary, (LPCSTR)1505);
int result = Bar(6,3);
printf("#1505(6,3) = %i\n", result);
FreeLibrary(hLoadedLibrary);

It looks strange, but you simply pass the Ordinal number instead of the exported name.

Interoperability with .NET and Other Languages

In the DemoAppManaged.exe project, I will import and use all three of the demo libraries:

  • DemoLib1 has a C++ mangled function name
  • DemoLib2 has a C mangled name
  • DemoLib3 has no mangling at all

Mangeled names

.NET is flexible, it seems to accept the name "Foo" also for the C mangled name, but other languages may not be so forgiving. So my recommendation is to export the names unmangled/undecorated. This is also how all the functions in the win32 libraries are exported.

VB6 Interoperability

At request, I will also mention interoperability with VB6.

The declaration is straight-forward, with a few pitfalls to lookout for. Below you will See the C++ exported function, followed by the same declaration in VB6.

C++
// extern is used in order to export it as a C function
// __stdcall to is used to conform to calling convention
extern "C"
{
  __declspec(dllexport) int __stdcall Mul(int a, int b);
}

// VB6 
Private Declare Function MyMul Lib "MoreMath.dll" Alias "Mul" _
(ByVal op1 As Long, ByVal op2 As Long) As Long

The VB6 code looks very similar to PInvoke declarations in .Net. You define a name for the function "MyMul", and specify both the DLL name, and the real exported name(called alias) "Mul".

The hard part is how to declare the parameters. The function is declared with Integer in C++, but why didn't I use Integer in VB6? The reason is simple. The two languages don't define Integer the same way. So we need to choose a datatype that is its equivalent. In VB6, Integers are 16 bits, and Longs are 32 bits. In C++ the general rule is that the size follows the size of the registers of the cpu. So Integers are 32 bits for the x86 architecture.

For further reading regarding VB6 declarations, please look at the following link Declare Statement

History

  • 25th May, 2014 - First version
  • 17thJune, 2014 - Second version
  • 8th Aug, 2014 - Third version

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect Visma Software AB
Sweden Sweden
Mattias works at Visma, a leading Nordic ERP solution provider. He has good knowledge in C++/.Net development, test tool development, and debugging. His great passion is memory dump analysis. He likes giving talks and courses.

Comments and Discussions

 
QuestionVisual Basic 6 Problem Pin
Etaningen30-Aug-20 18:17
Etaningen30-Aug-20 18:17 
GeneralMy vote of 4 Pin
KarstenK26-May-15 6:57
mveKarstenK26-May-15 6:57 
QuestionFYI Pin
Andy Bantly14-Aug-14 9:15
Andy Bantly14-Aug-14 9:15 
AnswerRe: FYI Pin
Mattias Högström15-Aug-14 0:30
Mattias Högström15-Aug-14 0:30 
GeneralRe: FYI Pin
Garth J Lancaster8-May-15 15:24
professionalGarth J Lancaster8-May-15 15:24 
GeneralRe: FYI Pin
Rick York21-Feb-17 11:15
mveRick York21-Feb-17 11:15 
QuestionContent typo? Pin
gerson0087-Aug-14 22:52
professionalgerson0087-Aug-14 22:52 
AnswerRe: Content typo? Pin
Mattias Högström8-Aug-14 10:39
Mattias Högström8-Aug-14 10:39 
GeneralRe: Content typo? Pin
gerson0088-Aug-14 19:42
professionalgerson0088-Aug-14 19:42 
QuestionC# / C++ LoadLibrary problem Pin
hughma20-Jun-14 1:22
hughma20-Jun-14 1:22 
AnswerRe: C# / C++ LoadLibrary problem Pin
Mattias Högström20-Jun-14 11:42
Mattias Högström20-Jun-14 11:42 
GeneralRe: C# / C++ LoadLibrary problem Pin
hughma23-Jun-14 0:36
hughma23-Jun-14 0:36 
GeneralRe: C# / C++ LoadLibrary problem Pin
Mattias Högström24-Jun-14 9:20
Mattias Högström24-Jun-14 9:20 
GeneralRe: C# / C++ LoadLibrary problem Pin
hughma24-Jun-14 22:58
hughma24-Jun-14 22:58 
SuggestionUse #pragma to avoid a .def file Pin
C Wernung18-Jun-14 21:45
C Wernung18-Jun-14 21:45 
GeneralRe: Use #pragma to avoid a .def file Pin
Mattias Högström19-Jun-14 3:31
Mattias Högström19-Jun-14 3:31 
GeneralRewind Pin
Guitar Zero18-Jun-14 11:32
professionalGuitar Zero18-Jun-14 11:32 
GeneralRe: Rewind Pin
Mattias Högström18-Jun-14 21:38
Mattias Högström18-Jun-14 21:38 
GeneralRe: Rewind Pin
Guitar Zero19-Jun-14 4:46
professionalGuitar Zero19-Jun-14 4:46 
GeneralRe: Rewind Pin
Mattias Högström19-Jun-14 8:12
Mattias Högström19-Jun-14 8:12 
GeneralRe: Rewind Pin
Guitar Zero19-Jun-14 9:08
professionalGuitar Zero19-Jun-14 9:08 
First off, I'm not a programmer. In fact, most of what I know I learned from writing amateur (and amateurish) Matlab and VBA macros and functions. The similarity between VBA and VB has been a huge help in getting started, but I'm far from good at writing. Things like "managed" and "unmanaged" code are mysteries to me, part of the strange language spoken by the practitioners of the magic I see but cannot do.

I inherited responsibility for a VB program and decided to make some enhancements to it. One of these changes uses some functions from the open-source BOOST math libraries--written in C++ and not easily ported to VB, at least not easily ported by me because of their complexity. I learned enough C++ to write a DLL to let me bridge the two languages. The DLL takes integers and integer arrays from the VB program, does some elementary math on the input, calls the functions from the BOOST library, and modifies one of the arrays. That array is then used by the VB program after the function in the DLL is completed. The array isn't explicitly passed back to the VB program. Instead, it's modified in place by the DLL.

Because of the way the arrays are handled, they are not thread safe and could (at least theoretically) be modified by some other thread writing to those memory locations. Consequently, it may work but it's sloppy. This hasn't been a problem yet, but it could be. Further, I plan to modify the program yet again to make it multi-threaded. Since I only know enough to be dangerous, I fear that I'll be increasing the odds of such an event. So, the first thing I need to do is fix the thread safety.

In any case, articles like yours sure make learning this stuff a lot easier. Thank you.
GeneralRe: Rewind Pin
Mattias Högström20-Jun-14 12:01
Mattias Högström20-Jun-14 12:01 
GeneralRe: Rewind Pin
Guitar Zero20-Jun-14 12:20
professionalGuitar Zero20-Jun-14 12:20 
GeneralRe: Rewind Pin
Mattias Högström20-Jun-14 20:02
Mattias Högström20-Jun-14 20:02 
GeneralRe: Rewind Pin
Guitar Zero20-Jun-14 6:51
professionalGuitar Zero20-Jun-14 6:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.