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?
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++ ...
There are several ways for a C++ application to invoke functions in a C# DLL.
- Using C++/CLI as an intermediate DLL
- http://blogs.microsoft.co.il/sasha/2008/02/16/net-to-c-bridge/
- 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
- Using COM
- http://msdn.microsoft.com/en-us/library/zsfww439.aspx
- 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
- 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
- Edit: Host a HTTP server and invoke via HTTP verbs (e.g. a REST style API)
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.
The easiest way is to use COM interop.
You could use a COM callable wrapper around your C# code compiled into a DLL.
As an alternate approach, you could use Lua to instantiate the CLR objects, execute, and return the results.