-->

Calling C# code from C++

2019-01-02 21:15发布

问题:

I need to be able to invoke arbitrary C# functions from C++. http://www.infoq.com/articles/in-process-java-net-integration 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?

回答1:

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



回答2:

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)


回答3:

If you don't care if your C++ program (or a portion of it) gets compiled with the /clr, you can use C++/CLI to simply call any .NET code (as long as you add a reference to it). Try out this article.

EDIT: Here is a nice tutorial

The other route is to make your C# code be exposed as COM.



回答4:

The easiest way is to use COM interop.



回答5:

You could use a COM callable wrapper around your C# code compiled into a DLL.



回答6:

As an alternate approach, you could use Lua to instantiate the CLR objects, execute, and return the results.



标签: