Calling method from an injected C# using another injected C++ library [duplicate] - c#

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?

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)

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

See DllExport.
IOW: The exact opposite of how DllImport works.
https://github.com/3F/DllExport
It has support for Windows, with cross-platform support in the works.
C# code (which we call from C++):
[DllExport]
public static int _add(int a, int b)
{
return a + b;
}
[DllExport]
public static bool saySomething()
{
DialogResult dlgres = MessageBox.Show(
"Hello from managed environment !",
".NET clr",
MessageBoxButtons.OKCancel
);
return dlgres == DialogResult.OK;
}
C++ code (which calls previous C# code):
typedef int(__cdecl *_add)(int a, int b);
typedef bool(__cdecl *saySomething)();
auto pAdd = (_add)GetProcAddress(lib, "_add");
int c = pAdd(5, 7);
auto pSaySomething = (saySomething)GetProcAddress(lib, "saySomething");
bool dlgres = pSaySomething();
And a YouTube video with a demo at Managed & Unmanaged; PInvoke; [ Conari vs DllExport]. To be honest, the documentation is a cut below perfect, but don't let that put you off: the YouTube videos are excellent.
This project is inspired by another project from Robert Giesecke which has 220,000 downloads on NuGet.
Fun fact: some Python libraries have used this to implement functionality in a mix of C++ and C#.
And finally, thank you Robert Giesecke and Denis Kuzmin, brilliant, brilliant work!

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

From Microsoft: Write a custom .NET Core host to control the .NET runtime from your native code.
IOW: Call C# from from C++ on both Windows and Linux.
There is sample code on GitHub.
This sample code is cross platform, it allows C# code in .NET Core to be called from any C++ application on both Linux and Windows.
In all honesty, this solution seems to be quite complicated compared to the other DllExport answer. The C++ code is doing a lot of heavy lifting to scan for resouces and entry points, etc. One argument for this answer could be that it is cross-platform. However, the other DllExport answer is also cross-platform as well, and a lot simpler to use.

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

Related

load C# dll in c++/cli and create a dll that works in unmanaged language

I have written a selenium script in C# and now I want to expose all functions and use them all in c++ code. My point is to deliver a dll to sb who wants to use this dll in pascal (delphi). The C# code is a complete code and all I want to do is to make a bridge between my C# and pascal.
I found out that pascal is an unmanaged language so C# code, which is a managed one, can not be consumed in pascal. For that reason, I started to write a c++ dll that uses my C# dll and makes a bridge between my C# and pascal code.
I've read all available topics on stackoverflow and these are what I've found useful:
expose my functions using COM
using c++/cli to communicate with my C# dll.
I started with the first one. I was able to create COM visible dll and use that in my c++ native code but I had problems with data types. I found it hard and moved on to the second option. But I'm not sure if I can wrap all my functions like that and let unmanaged languages use them.
a sample of my c# code:
namespace MainEngine
{
public static class StartMainEngine
{
public static void test_pascal(out string _result)
{
_result = "Hello World!";
}
}
}
my c++/cli code(I have referenced to my dll and visual studio shows me all functions inside my dll. So, It's not a dll import issue):
#using<ManagedLibrary.dll>
using namespace MainEngine;
char* r;
StartMainEngine::test_pascal(r);
Please guide me through this and let me know if I'm doing this in the correct way to be able to consume this dll in pascal.
It's possible using COM, CLR or IPC
Full answer you can find in this topic here

Whats the best to call QuantLib methods from C#

I am gonna use QuantLib in C# app (http://quantlib.org/docs.shtml) but I don't trust their .NET conversion project (too immature).
I need only options valuation part.
anyone used it in managed app? whats the best approach?
What I have done in a similar situation is implementing a C++ native dll as an adapter between the C# and C++ projects.
From C# you can access your dll interface with DllImport.
In the dll you can reach the full C++ interface, but it is worth simplifying it to your exact needs on the managed site.
Example:
// in the C++ dll:
extern "C" MY_API void SetInput(double* Values, int Count);
// in C#:
[DllImport("MyStuff.dll")]
public extern static void SetInput(double[] Values, int Count);
C# wrappers for the C++ library are already available and are distributed at the QuantLib download page (these are wrappers as suggested by jmihalicza, not the ongoing C# port you're referring to in your question). The distribution also contains an example of option valuation (look under the CSharp/examples folder).

Writing a C++ DLL that a C# .NET Application can call?

This is the situation. I am writing a backend application in C++ and my colleagues are using C# for the frontend. Basically, my backend application does image processing on images received from the C# frontend and returns a text file with data about the image.
What we were doing earlier was writing the images to disk and calling the C++ application with the file path of the image as a parameter. However, this writing/reading from disk has become a bottleneck, so we are wanting to convert the C++ application to a DLL.
At the basic level, what I want is to expose a single method from my C++ application to the C# one through a DLL (the C# application is web-based):
int ProcessImage(System::Bitmap^ image, System::String ^results)
How can I go about doing this? I am using VC++ Express 2008 and my C++ code currently compiles with CLR (although I have mixed a lot of native C++ code inside).
I have been looking around on the web, but am still stuck on how to do this. I think a C++/CLI DLL is the best option, but how do I do this?
Writing a DLL in C/C++ for .Net interoperability
If you label your C++ function as a "C" function, then it can be called by PInvoke.
Your C function will look like this:
extern "C" __declspec(dllexport) int Test() {
return 1;
}
Your C# reference will be like this:
[DllImport("test.dll")]
public static extern int Test();
If you C++ function is an instance member, then you can still do it but it requires some tricks.
I finally figured it out. What you need to do is:
In your C++ project, set the option in Visual C++ to compile with clr pure, which makes the project a C++/CLI one
In your C++ project, expose methods by creating a public ref class:
public ref class Interop
{
public:
//! Returns the version of this DLL
static System::String^ GetVersion() {
return "3.0.0.0";
}
//! Processes an image (passed by reference)
System::Int32^ Process(Bitmap^ image);
}
In a C# program, add a reference to the C++ DLL you compiled
In the C# program, call these methods (i.e. Interop::Process(myBitmapInCS))
I believe this method is called "implicit P/Invoke"
Hope this helps!

talking to C from C#

I have a legacy code implemented in C (not C++). I would like to be able to call a few methods in this C code from my C# code (on Windows). What would be the best approach to interface between the two language? Please note that the method in C is not stateless. We need to call two methods:
initialization() => this will initialize the data structure and load data from files into memory. This method will be called once.
ComputeSomething(parameters) => there will be several calls from C# to this method.
Note: These two methods actually call several other methods but these are only the two methods that we would like to expose to C# (the code is quite complicated, that's why we do not want to port to C#)
I have been able to import the c code into visual studio and able to compile the code successfully. I know that we can probably implement the C code as windows service but I am looking for a solution that allow us to call C method from C# directly. Any pointers is highly appreciated! (is COM interop related to what I am looking to do?)
Sounds like you can use P/Invoke for this. Check out this site for tips:
http://www.pinvoke.net/
Also, try searching SO for advice on P/Invoke and Google for
c# pinvoke calling c code
I don't have any technical examples at hand, but I have written some .NET code which called Win32 API's via P/Invoke. The tricky part is getting the method signatures correct when passing parameters. This might help you out there.
Recent version of Visual Studio allow you to write C++ code that can call unsafe functions but still interface with CLR managed code. They call this "Implicit PInvoke," or "C++/CLR." Check out the MSDN article "Using C++ Interop" to learn more.
Managed code can't call unmanaged directly, so you need wrapper functions to handle the memory management issues and to translate between .NET objects and the data structures of your application. From the link above, check out the section on "How to: Wrap Native Class for Use by C#."
Here is a solution. The solution allows to call C# function from C by decorating your function with [DllExport] attribute (opposite of P/Invoke DllImport).
https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports
C# code
class Test
{
[DllExport("add", CallingConvention = CallingConvention.StdCall)]
public static int Add(int left, int right)
{
return left + right;
}
}
C code
int main()
{
int z = add(5,10);
printf("The solution is found!!! Z is %i",z);
return 0;
}

What's the difference between managed C++ and C#?

The major advantage I see for using C++ instead of C# is compiling to native code, so we get better performance. C# is easier, but compiles to managed code.
Why would anyone use managed C++ for? What advantages it gives us?
Managed C++ and C++/CLI allow you to easily write managed code that interacts with native C++.
This is especially useful when migrating an existing system to .Net and when working in scientific contexts with calculations that must be run in C++.
Managed c++ allows to more easily interop between native code, and managed code. For instance, if you have a library in c++ (.cpp files and .h files), you can link them into your project, and create the appropriate CLR objects, and simply call the native code from within your CLR objects:
#include "yourcoollibrary.h"
namespace DotNetLibraryNamespace
{
public ref class DotNetClass
{
public:
DotNetClass()
{
}
property System::String ^Foo
{
System::String ^get()
{
return gcnew System::String(c.data.c_str());
}
void set(System::String ^str)
{
marshal_context ctx;
c.data = ctx.marshal_as<const char *>(str);
}
}
private:
NativeClassInMyCoolLibrary c;
};
}
(c++/cli is the new name) You can wrap native code to work flawlessly with garbage controlled c# and even process callbacks too. Inversely you can create managed types and interact with them from c++.
Allows developers to migrate to c# easily to pilot fast build times and so on, e.g. xna, linking to native libraries, as mentioned!

Categories