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!
Related
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
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.
I have just started a C# project and want to import a C++ .lib and it's corresponding header (.h) file.
I've read various posts that all mention .dll, rather than .lib, which is confusing me.
The image below shows the .lib and .h file I'm referring to, all I've done is drag them into the project.
Can anyone point me to a clearer explanation of how to go about doing this? I'm sure it can't be as hard as it seems.
This is, unfortunately, a non-trivial problem.
The reason is primarily due to the fact that C++ is an unmanaged language. C# is a managed language. Managed and unmanaged refers to how a language manages memory.
C++ you must do your own memory management (allocating and freeing),
C# .NET Framework does memory management with a garbage collector.
In your library code
You must make sure all of the places you call new, must call delete, and the same goes for malloc and free if you are using the C conventions.
You will have to create a bunch of wrapper classes around your function calls, and make sure you aren't leaking any memory in your C++ code.
The problem
Your main problem (to my knowledge) is you won't be able to call those functions straight in C# because you can't statically link unmanaged code into managed code.
You will have to write a .dll to wrap all your library functions in C++. Once you do, you can use the C# interop functionality to call those functions from the dll.
[DllImport("your_functions.dll", CharSet = CharSet.Auto)]
public extern void your_function();
What you could do, is creating a C++/CLI wrapper and expose the functionality of the lib you want to use via your wrapper. The created wrapper dll you can easily reference in your C# project. This of course takes a little bit of work to create the managed/unmanaged wrapper, but will pay off in the long run.
To create a managed C++ project select under the C++ project templates CLR and Class Library. Here you can link to your lib, use the header file the way you are used to.
Next create a new class (ref class) and wrap your library in it. An example might look something like this:
LibHeader.h
int foo(...);
You write a wrapper class like this:
Header:
Wrapper.h
public ref class MyWrapper
{
public:
int fooWrapped();
};
Your Implementation:
Wrapper.cpp
#include Libheader.h
int MyWrapper::fooWrapped()
{
return foo();
}
Namespaces and all the good stuff omitted for simplicity.
Now you can use MyWrapper in your C# code just as easy as any other managed class. Of course when the interface of the lib gets more complicated you have to think about it a bit more, but it might help to separate the lib-code from your application. Hope to have shed some light on it.
It is 'as hard as it seems'. C++ and C# are ambivalent. The first has deterministic destruction, the second not. Now, you write C++/cli delaying the destruction to some finalizer called by the garbage collector working in it's own thread, introducing problems all over the place (thread safety, are C++ members (used in c++/cli) valid?, ...). Even worse the GC might suggest C++ objects being tiny (a pointer) and provoke a kind of memory leak (due to late deallocating tiny objects). Essentially you end up in writing a GC on top of the C++/cli GC to delete non C++/cli (!) objects in the main thread or another. All that is insane, ...
My friend and I have put together a C# run-time library which we want to compile, or convert, into a .dll in native assembly code and call from a C++ application.
I suspected we might not be the first ones embarking on this type of an effort. So I looked around and came up with the following:
How to migrate from C++ COM to C++CLI
Managed C++ wrappers for legacy C++ libraries
Writing a managed wrapper for unmanaged (C++) code - custom types/structs
how to convert C# to C++
http://bytes.com/topic/c-sharp/answers/268197-convert-c-form-c-net
However, these links all talk about how to port C++ code to CLI or C#. There is no mention of how to port C# managed code to a standalone .dll library in native assembly callable from a C++ application.
Any thoughts?
Best regards,
Baldur
Essentially you need an unmanaged wrapper around a managed library, which is the opposite of the more common problem.
The basic idea is to create a C++ library that has unmanaged exports (native C-style functions) but internally used managed C++ to interact with your library.
Be aware that marshalling unmanaged data across layers may be tricky - hopefully you only need to use very basic types (strings and numbers).
Also note that the client will still need to have the appropriate .NET framework installed - wrapping the library will not get around that requirement.
Here's a few links that may help:
Calling a C# function from unmanaged C++
Using managed code in an unmanaged application
The keyword for your problem COM Component in C++ look the example below:
You can regsiter your .Net assembly with COM after that you can call it from C++.
See the example below:
[Guid(123565C4-C5FA-4512-A560-1D47F9FDFA20")]
public interface ISomeInteface
{
[DispId(1)]
string FirstFunction{ get; }
[DispId(2)]
void SecondFunction();
}
[ComVisible(true)]
[Guid(123565C4-C5FA-4512-A560-1D47F9FDFA20")]
[ClassInterface(ClassInterfaceType.None)]
public sealed class SomeInteface: ISomeInteface
{
public SomeInteface()
{
}
public string FirstFunction
{
get { return "Work here"; }
}
public void SecondFunction()
{
}
}
More info;You can take a look in the following links:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/440aca96-288a-4d5c-ab9a-87ea2cdd5ca8/how-to-call-c-dll-from-c
http://support.microsoft.com/kb/828736
I have just started a C# project and want to import a C++ .lib and it's corresponding header (.h) file.
I've read various posts that all mention .dll, rather than .lib, which is confusing me.
The image below shows the .lib and .h file I'm referring to, all I've done is drag them into the project.
Can anyone point me to a clearer explanation of how to go about doing this? I'm sure it can't be as hard as it seems.
This is, unfortunately, a non-trivial problem.
The reason is primarily due to the fact that C++ is an unmanaged language. C# is a managed language. Managed and unmanaged refers to how a language manages memory.
C++ you must do your own memory management (allocating and freeing),
C# .NET Framework does memory management with a garbage collector.
In your library code
You must make sure all of the places you call new, must call delete, and the same goes for malloc and free if you are using the C conventions.
You will have to create a bunch of wrapper classes around your function calls, and make sure you aren't leaking any memory in your C++ code.
The problem
Your main problem (to my knowledge) is you won't be able to call those functions straight in C# because you can't statically link unmanaged code into managed code.
You will have to write a .dll to wrap all your library functions in C++. Once you do, you can use the C# interop functionality to call those functions from the dll.
[DllImport("your_functions.dll", CharSet = CharSet.Auto)]
public extern void your_function();
What you could do, is creating a C++/CLI wrapper and expose the functionality of the lib you want to use via your wrapper. The created wrapper dll you can easily reference in your C# project. This of course takes a little bit of work to create the managed/unmanaged wrapper, but will pay off in the long run.
To create a managed C++ project select under the C++ project templates CLR and Class Library. Here you can link to your lib, use the header file the way you are used to.
Next create a new class (ref class) and wrap your library in it. An example might look something like this:
LibHeader.h
int foo(...);
You write a wrapper class like this:
Header:
Wrapper.h
public ref class MyWrapper
{
public:
int fooWrapped();
};
Your Implementation:
Wrapper.cpp
#include Libheader.h
int MyWrapper::fooWrapped()
{
return foo();
}
Namespaces and all the good stuff omitted for simplicity.
Now you can use MyWrapper in your C# code just as easy as any other managed class. Of course when the interface of the lib gets more complicated you have to think about it a bit more, but it might help to separate the lib-code from your application. Hope to have shed some light on it.
It is 'as hard as it seems'. C++ and C# are ambivalent. The first has deterministic destruction, the second not. Now, you write C++/cli delaying the destruction to some finalizer called by the garbage collector working in it's own thread, introducing problems all over the place (thread safety, are C++ members (used in c++/cli) valid?, ...). Even worse the GC might suggest C++ objects being tiny (a pointer) and provoke a kind of memory leak (due to late deallocating tiny objects). Essentially you end up in writing a GC on top of the C++/cli GC to delete non C++/cli (!) objects in the main thread or another. All that is insane, ...