Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C# code from C++

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?

like image 574
Gili Avatar asked Apr 22 '09 18:04

Gili


People also ask

What is calling function in C?

When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

Can you call C from C++?

Just declare the C function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code.

Can I call C from rust?

Rust can link to/call C functions via its FFI, but not C++ functions.


2 Answers

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)
like image 111
cdiggins Avatar answered Sep 20 '22 23:09

cdiggins


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

like image 41
Ðаn Avatar answered Sep 22 '22 23:09

Ðаn