Tutorial for an MC++ library with a native API


This are the steps to build a 'Managed Extension for C++ .NET' library (assembly) with a native API.
This native API can be called by any classic (e.g. C++/Win32) code that can call DLL entry points.
Please read the warnings at the bottom of this page.

In this tutorial the library will have just two sample APIs, one for Console and one for GUI.
You can download this source-code as MCppLibWithAPI.zip


Open Visual Studio .NET (2003) and create a new project, using the C++ template [Class Library (.NET)]:

then let's just add a simple .NET Windows Form, named MyMCppForm:


Now we define the native API in a .H header file, thus in the project tree, click 'Add New Item',
select the template [Header File (.h)], name the file as MCppLibAPI.h:

use the classic well-known __declspec techniques for import & export,
and a macro depending on a preprocess define, here named MCPPLIB_BUILD.


Open the project settings, add the preprocessor-define MCPPLIB_BUILD:


In the project tree, click to insert a new item.
Select the template [Module-Definition File (.def)], name it e.g. DllExports.def.

Add an EXPORTS section with the API names (exactly as in .h, non-decorated).


Open the project settings, verify the .DEF file was added:


Finally, add some implementation source-code to the file MCppLib.cpp:

Rebuild the project. Done!
(don't forget to make the project settings changes for both, debug & release build!)

 


Important Please note the following issue: Mixed DLL loading problem

KB - Linker Warnings When You Build Managed Extensions for C++ DLL Projects

Semicolon - Finding bugs the hard way

MSDN - Mixed DLL Loading Problem

While there is a partial workaround for VC++.NET 2003, only VS2005 will solve the problem:
Invoking MSIL Functions under Loader Lock in Microsoft Visual C++ 2005
 


NETMaster Thomas Scheidegger