Skip to content

Exporting DLL functions

Pavel Anisko edited this page Mar 23, 2018 · 1 revision

NuGet package UnmanagedExports by Robert Giesecke is used to export C# DLL functions in C++ style. The documentation is at UnmanagedExports home page. Theoretically, any other NuGet package providing the same functionality or any other way should also work, but this tutorial uses UnmanagedExports. The demo plug-in also uses it (v1.2.7).

So, in order to export DLL function using UnmanagedExports, these steps must be accomplished:

  1. Include UnmanagedExports package in your project. Just right-click on the project in Visual Studio, select "Manage NuGet packages...", find the package and install it. Official doc explains this in details and pictures.
  2. Set the building platform for your project to x86 (32-bit) or x64 (64-bit) (project properties, "Build" tab). AnyCPU is not OK, because AnyCPU assemblies cannot export functions. Note: The demo plug-in uses x86.
  3. Include RGiesecke.DllExport namespace — this comes from UnmanagedExports.
  4. Include System.Runtime.InteropServices — this is C# namespace.
  5. Make the desired method public static.
  6. Decorate the desired method with [DllExport].

Important: The function will be exported with the name, specified in [DllExport], not the actual method name. Both names can match, but not necessarilly. See UnmanagedExports home page for usage details.

The resulting C# code should look like this:

using System;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;

namespace DemoPluginNet
{
    public class DemoPlugin
    {
        ...
        [DllExport("IdentifyPlugIn", CallingConvention = CallingConvention.Cdecl)]
        public static string IdentifyPlugIn(int id)
        {
        }
        ...
    }
}

After DLL has been built, you can validate, whether exports succeeded.

Hint: Sometimes it is not possible to install UnmanagedExports package in Visual Studio due to security policy restrictions (PowerShell scripts are not allowed to run). This may occur, for instance, when you are at workplace. To workaround this issue, prepare an empty project with UnmanagedExports package pre-installed at home and just copy it to the destination PC.

Clone this wiki locally