Calling C# code from C++

Solution 1:

There are several ways for a C++ application to invoke functions in a C# DLL.

  1. Using C++/CLI as an intermediate DLL
    • http://blogs.microsoft.co.il/sasha/2008/02/16/net-to-c-bridge/
  2. Reverse P/Invoke
    • http://tigerang.blogspot.ca/2008/09/reverse-pinvoke.html
    • http://blogs.msdn.com/b/junfeng/archive/2008/01/28/reverse-p-invoke-and-exception.aspx
  3. Using COM
    • http://msdn.microsoft.com/en-us/library/zsfww439.aspx
  4. Using CLR Hosting (ICLRRuntimeHost::ExecuteInDefaultAppDomain())
    • http://msdn.microsoft.com/en-us/library/dd380850%28v=vs.110%29.aspx
    • http://msdn.microsoft.com/en-us/library/ms164411%28v=vs.110%29.aspx
    • https://stackoverflow.com/a/4283104/184528
  5. Interprocess communication (IPC)
    • How to remote invoke another process method from C# application
    • http://www.codeproject.com/Tips/420582/Inter-Process-Communication-between-Csharp-and-Cpl
  6. Edit: Host a HTTP server and invoke via HTTP verbs (e.g. a REST style API)

Solution 2:

Compile your C++ code with the /clr flag. With that, you can call into any .NET code with relative ease.

For example:

#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    System::DateTime now = System::DateTime::Now;
    printf("%d:%d:%d\n", now.Hour, now.Minute, now.Second);

    return 0;
}

Does this count as "C++"? Well, it's obviously not Standard C++ ...

Solution 3:

See DllExport.

IOW: The exact opposite of how DllImport works.

https://github.com/3F/DllExport

It has support for Windows, with cross-platform support in the works.

C# code (which we call from C++):

[DllExport]
public static int _add(int a, int b)
{
    return a + b;
}

[DllExport]
public static bool saySomething()
{
    DialogResult dlgres = MessageBox.Show(
        "Hello from managed environment !",
        ".NET clr",
        MessageBoxButtons.OKCancel
    );

    return dlgres == DialogResult.OK;
}

C++ code (which calls previous C# code):

typedef int(__cdecl *_add)(int a, int b);
typedef bool(__cdecl *saySomething)();

auto pAdd = (_add)GetProcAddress(lib, "_add");
int c = pAdd(5, 7);

auto pSaySomething = (saySomething)GetProcAddress(lib, "saySomething");
bool dlgres = pSaySomething();

And a YouTube video with a demo at Managed & Unmanaged; PInvoke; [ Conari vs DllExport]. To be honest, the documentation is a cut below perfect, but don't let that put you off: the YouTube videos are excellent.

This project is inspired by another project from Robert Giesecke which has 220,000 downloads on NuGet.

Fun fact: some Python libraries have used this to implement functionality in a mix of C++ and C#.

And finally, thank you Robert Giesecke and Denis Kuzmin, brilliant, brilliant work!