tags:

views:

1664

answers:

5

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?

+3  A: 

The easiest way is to use COM interop.

chris
IJW (C++ interop) is far easier than COM interop.
codekaizen
See the help at http://msdn.microsoft.com/en-us/library/zsfww439.aspx
crimson13
+3  A: 

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

Dan
Then it no longer is C++ calling C#, it's C++/CLI calling C# - you've sidestepped the question. C++ vs. C++/CLI is a very important distinction that should not be glossed over.
Not Sure
Can't you export C++/CLI functions so they're so that they're callable from normal C++ code?Dan, can you post an example showing how to invoke C# code from C++/CLI?
Gili
C++/CLI can call any C# function as if it were a "regular" C++ function. Add your references, /clr and It Just Works.
Filip
Dan, please add "#include <tchar.h>#include <stdio.h>" to the above code block.
Gili
"Does this count as C++? Well, it's obviously not Standard C++"... The point is that normal C/C++ code should be able to invoke C++/CLI which in invokes C#. Seeing how this works I'm quite happy with this solution.
Gili
+5  A: 

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.

Filip
Good answer, bad tutorial. Please link to a better tutorial if possible :)
Gili
A: 

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

Dan Vinton
A: 

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

David Robbins