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!
Asked
Active
Viewed 229 times
-1
-
Just to clarify, you want a way to use a C# .NET code in a C++ normal (not CLI) project? – Roy Avidan Aug 14 '20 at 23:13
-
Correct--yeah (use C# code from unmanaged C++ project) – Zachary Zhu Aug 14 '20 at 23:18
-
Maybe this link will be helpful? https://www.codeproject.com/Tips/695387/Calling-Csharp-NET-methods-from-unmanaged-C-Cplusp – Roy Avidan Aug 14 '20 at 23:28
1 Answers
0
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

Roy Avidan
- 769
- 8
- 25
-
Sorry, to specify: how can I import the class wholesale instead of on a method by method by basis? – Zachary Zhu Aug 14 '20 at 23:46
-
I don't think you can, but it's C++, so you can create a copy of the class with `_declspec(dllexport)` for each function and import it into a header file. It's a lot of work to mix managed and unmanaged code and that's why usually people use just `C++/CLI` for this, or create an unmanaged DLL and use it in C# with `DllImportAttribute` – Roy Avidan Aug 14 '20 at 23:55