I’m a bit rusty, actually really rusty with my C++. Haven’t touched it since Freshman year of college so it’s been a while.
Anyway, I’m doing the reverse of what most people do. Calling C# code from C++. I’ve done some research online and it seems like I need to create some managed C++ to form a bridge. Use __declspec(dllexport) and then create a dll from that and use the whole thing as a wrapper.
But my problem is – I’m really having a hard time finding examples. I found some basic stuff where someone wanted to use the C# version to String.ToUpper() but that was VERY basic and was only a small code snippet.
Anyone have any ideas of where I can look for something a bit more concrete? Note, I do NOT want to use COM. The goal is to not touch the C# code at all.
While lain beat me to writing an example, I’ll post it anyhow just in case…
The process of writing a wrapper to access your own library is the same as accessing one of the standard .Net libraries.
Example C# class code in a project called CsharpProject:
You would create a managed C++ class library project (example is CsharpWrapper) and add your C# project as a reference to it. In order to use the same header file for internal use and in the referencing project, you need a way to use the right declspec. This can be done by defining a preprocessor directive (
CSHARPWRAPPER_EXPORTSin this case) and using a#ifdefto set the export macro in your C/C++ interface in a header file. The unmanaged interface header file must contain unmanaged stuff (or have it filtered out by the preprocessor).Unmanaged C++ Interface Header file (CppInterface.h):
Then you can create an internal header file to be able to include in your managed library files. This will add the
using namespacestatements and can include helper functions that you need.Managed C++ Interface Header file (CsharpInterface.h):
Then you just write your interface code that does the wrapping.
Managed C++ Interface Source file (CppInterface.cpp):
Then just include the unmanaged header in your unmanaged project, tell the linker to use the generated .lib file when linking, and make sure the .Net and wrapper DLLs are in the same folder as your unmanaged application.