How can I design a wrapper class for consuming a C++ application to use a C# DLL?

282 views Asked by At

I followed the following tutorial, https://www.red-gate.com/simple-talk/dotnet/net-development/creating-ccli-wrapper/, to create an instance of a C++ static library from C# .NET framework console application using a wrapper class. In this tutorial, the ManagedObject.h file creates a template for wrapper classes from unmanaged to managed. How would I create a template to go from managed to unmanaged--if this isn't possible, any links to create a wrapper class to go from a C# DLL to be used by a C++ application would be much appreciated!

1

There are 1 answers

2
Roy Avidan On

Like in the link you mentioned, it seems that the only way to do so is to create 3 projects.

To start, create a C# Class Library project and create some public libraries, for example:

Commands.cs:

using System;
public static class Commands
{
    public static void PrintMsg() => Console.WriteLine("Hello");
}

Then, create a C++/CLI project (the wrapper project). In the wrapper project, create some functions to use your classes and export them (I'm not sure if extern "C" is required but i will use it).

wrapper.cpp:

extern "C" __declspec(dllexport) void printMsg()
{
    Commands::PrintMsg();
}

In your C++ unmanaged project, reference your wrapper project and import the functions (and use them).

main.cpp:

extern "C" __declspec(dllimport) void printMsg();

int main()
{
    printMsg();
    return 0;
}

Output: Hello