Search code examples
c#c++-cliinterop

Calling C# code from C++, but ExecuteInDefaultAppDomain() is too limited


I need to be able to invoke arbitrary C# functions from C++. In-process Interoperability suggests using ICLRRuntimeHost::ExecuteInDefaultAppDomain(), but this only allows me to invoke methods having this format: int method(string arg)

What is the best way to invoke arbitrary C# functions?


Solution

  • 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++ ...