This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's the difference between a non-unmanaged type and a managed type?
I was recently working on an application in C++ and I came across something called managed types, native types, marshaling etc. I am not quite sure what these terms mean. From what I have been reading, it seems that we have managed types in c++ to allow access to some .Net features (.Net native types) and we use marshaling to convert from managed types to native types (vice versa). Am I correct? thanks~
Managed C++ was/is a Microsoft creation. Applications developed using the managed C++ framework operate within a virtual-machine environment the same way that .NET applications do. This provides facility such as more run-time checking, memory allocation. Also, the VM provided garbage collection just like .NET does for C#. The limitation with the managed framework is that it the VM did not support multiple inheritance (C# does not support multiple inheritance). Therefore managed C++ development was restricted.
Marshaling is also called serialisation where objects are converted to other "simple" types for transmitting to other processes or machines via RPCs.
Related
This question already has answers here:
Call C# dll from Delphi
(3 answers)
Closed 7 years ago.
As my first time as a student employee programming I have to create a DLL in C#.NET which is callable from Delphi.
I've read about this being not so easy due to Delphi being native code and .NET being managed.
I've also read about 'Unmanaged Exports' from Robert Giesecke. Could this be the solution?
Since I do not have Delphi on my machine (Delphi isn't free), I can't test this out for myself.
Also, will I have problems with my datatypes when I implement the Unmanaged Exports?
Last but not least, is there a language I could use that would have the same problem as Delphi for loading the DLL? It'd be nice for me to be able to test.
UnmanagedExports is one option. It certainly works very well. Other options include:
Exposing the functionality using COM.
Exposing the functionality via a C++/CLI mixed mode assembly.
Hosting the CLR from your Delphi code.
The final option is not very tractable. Don't attempt to do that.
You'll almost certainly encounter problems with interop data types unless you are already an expert in the field.
You can certainly test this out with FreePascal. Very likely you can write code in FreePascal that consumes your .net assembly and later use the exact same code in Delphi. Even if you have to change it somewhat, the lessons you will learn will be exactly the same.
You can make your .Net DLL as Com visible. Check this link.
Delphi can load Com objects without problems. This in theory, I don't have specific code samples, but you can try with different tutorials, they practically explains the same.
I don't know about the data types, but COM always tries to cast to a base type (double, float to decimal, number to integer, and complex objects to dynamic objects).
You can use the .Net Runtime Library for Delphi in http://dotnetruntimelibraryfordelphi.sourceforge.net/
The runtime library allows you to host and access .net library types.
This question already has answers here:
Wrapping C++ for use in C#
(3 answers)
Closed 9 years ago.
I have a C++ project which consists of some headers, cpps, some lib files and DLL files.
I want to wrap these files in order to use them on a C# project.
I wanted to make one DLL which will contain the all C++ project and then to wrap it with C# class so I would be able to work with it.
So my questions are (Working with Visual Studio 2010):
How do I make the final DLL file.
a. I know how to link the lib files to the project, but how do i link the DLLs?
b. What do I need to add to my headers in order that the functions declared in them (which are implemented in the lib files) will be imported to the DLL. (What is __declspec)?
After building the final DLL file, how do I create a C# project which use this DLL file?
Thanks in advance
This is called (COM) InterOp. Fortunately one of the major design goals of the original .NET Framework was to facilitate easy interoperability between managed and unmanaged code. Broadly speaking there are three different kinds of interoperability that one may wish to achieve when dealing with managed code.
Making calls into COM components from managed code
Making calls into native DLLs from managed code. This known as platform invocation or colloquially, PInvoke. (This is what you want)
Allowing COM components to call managed code by wrapping the managed code with a runtime callable wrapper (RCW). This can be used as a strategy for the piecemeal replacement of legacy code on a planned basis.
The process by which data is moved from the managed to unmanaged realm is known as marshalling. This is the name by which data and its associated types are serialised across some boundary or other. To support this process there are a collection of classes that exist under the System.Runtime.InterOp namespace.
Broadly speaking the process is essentially as follows:
Determine function names (I use Dependency Walker)
Determine function signatures (Look it up on MSDN if it's a MSFT one)
Determine data types and structures required by code
Write managed code to call into the native code that satisfies the criteria determined above
Test the wrapper code that's after being written to ensure that it produces the expected results (this can often be the most tedious part)
You are looking for C++/CLI. With this hybrid you can write a dll that can contain any amount of normal C++ code and it can contain managed classes that can use .NET types (like System.String) for it's interface and internally handle your normal C++ types. That dll will be usable from C# like any other .NET dll. From the calling programs perspective will look as if you had written it in C#.
Normally answers should contain practical examples, but C++/CLI is a large field to cover, you could write books just describing your scenario. You can find a good tutorial here and a good Overview here.
I know this is a strange question but the idea is simple: I prefer C# syntax rather than C++:
-Setters and getters directly inside a property
-interfaces
-foreach statement
-possibility to declare an implicit cast operator
other small things...
What I really don't know is if is possible to import a c++ dll (expecially std libraries) in C# if I don't use any namespace (even System)
The idea is just to write a program using everything that you will normally use in C++ (nothing from CLR so), even printf for example
Thanks for any answer
No it is not possible to simply import existing C or C++ files into a C# project. They are very different languages and cannot be mixed at the source level.
The way to mix C# and C++/C applications is at the PInvoke or COM Interop level. This works by duplicating the signatures in C# and allowing the C# compiler to determine the binary layout of the native type in order to marshal between the languages.
There's now something close to this
.NET Native compiles C# to native machine code that performs like C++. You will continue to benefit from the productivity and familiarity of the .NET Framework with the great performance of native code.
It's for Windows Store apps only (desktop apps may come in the future):
Desktop apps are a very important part of our strategy. Initially, we are focusing on Windows Store apps with .NET Native. In the longer term we will continue to improve native compilation for all .NET applications.
And
apps will get deployed on end-user devices as fully self-contained natively compiled code (when .NET Native enters production), and will not have a dependency on the .NET Framework on the target device/machine
No; this is not directly possible. In particular, C++ templates are not supported by C#.
I'm trying to write integrations with the operating system and with things like active directory and Ocropus.
I know a bunch of programming languages, including those listed in the title. I'm trying to learn exactly how C++/CLI works, but can't find succinct, exact and accurate descriptions online from the searching that I have done. So I ask here.
Could you tell me the pitfalls and features of C++/CLI? Assume I know all of C# and start from there. I'm not an expert in C++, so some of my questions' answers might be "just like C++", but could say that I am at C#. I would like to know things like:
Converting C++ pointers to CLI pointers,
Any differences in passing by value/doubly indirect pointers/CLI pointers from C#/C++ and what is 'recommended'.
How do gcnew, __gc, __nogc work with
Polymorphism
Structs
Inner classes
Interfaces
The "fixed" keyword; does that exist?
Compiling DLLs loaded into the kernel with C++/CLI possible? Loaded as device drivers? Invoked by the kernel? What does this mean anyway (i.e. to load something into the kernel exactly; how do I know if it is?)?
L"my string" versus "my string"? wchar_t? How many types of chars are there?
Are we safe in treating chars as uint32s or what should one treat them as to guarantee language indifference in code?
Finalizers (~ClassName() {}) are discouraged in C# because there are no garantuees they will run deterministically, but since in C++ I have to use "delete" or use copy-c'tors as to stack allocate memory, what are the recommendations between C#/C++ interactions?
What are the pitfalls when using reflection in C++/CLI?
How well does C++/CLI work with the IDisposable pattern and with SafeHandle, SafeHandleZeroOrMinusOneIsInvalid?
I've read briefly about asynchronous exceptions when doing DMA-operations, what are these?
Are there limitations you impose upon yourself when using C++ with CLI integration rather than just doing plain C++?
Attributes in C++ similar to Attributes in C#?
Can I use the full meta-programming patterns available in C++ through templates now and still have it compile like ordinary C++?
Have you tried writing C++/CLI with boost?
What are the optimal ways of interfacing the boost library with C++/CLI; can you give me an example of passing a lambda expression to an iterator/foldr function?
What is the preferred way of exception handling? Can C++/CLI catch managed exceptions now?
How well does dynamic IL generation work with C++/CLI?
Does it run on Mono?
Any other things I ought to know about?
Note: I'm really asking about the peculiarities of C++/CLI, its trapdoors.
Converting C++ pointers to CLI pointers
CLI types don't have to be pointers. In C++/CLI handle (^) is used.
Any differences in passing by
value/doubly indirect pointers/CLI
pointers from C#/C++ and what is
'recommended'.
If you need better interoperability with C#, avoid using pointers. Use all the pointer related stuff in C++/CLI and expose only managed types so that C# applications can use it easily.
The "fixed" keyword; does that exist?
pin_ptr<> is the equivalent.
Finalizers (~ClassName() {}) are
discouraged in C# because there are no
garantuees they will run
deterministically, but since in C++ I
have to use "delete" or use
copy-c'tors as to stack allocate
memory, what are the recommendations
between C#/C++ interactions?
C++/CLI supports deterministic resource management. When you write a destructor, compiler will implement IDisposable interface on the class and convert destructor into Dispose() method. delete will call this Dispose() to do the resource de-allocation. Because of this, you don't have issues in using it from C#. You can wrap the usage in using statement in C# which will ensure call on Dispose.
Attributes in C++ similar to
Attributes in C#?
Yes they are similar.
Can I use the full meta-programming
patterns available in C++ through
templates now and still have it
compile like ordinary C++?
Yes. C++/CLI supports templates on ref classes. You can use metaprogramming techniques like you do in standard C++. But these won't be portable to C#.
Have you tried writing C++/CLI with
boost?
C++/CLI has access to the whole .NET framework. I don't think boost helps much here.
To start with, you're confusing the now-defunct "Managed extensions for C++" which had __gc and __nogc keyword, with the new and currently supported C++/CLI language, which finally provides a proper distinction between pointers (native) and handles (managed objects, they're actually implemented as pointers into garbage collected memory where .NET objects live, but you shouldn't think of them as pointers because they get adjusted automatically by the garbage collector). The two types of pointers are completely distinct, only builtin types are compatible with both and then you just box them to get a handle. You can never have a handle pointing outside the managed heap and you can only get a native pointer into the managed heap for the duration of a pin_ptr lifetime (local scope only). A managed class can hold a pointer to native memory, just like C# can have IntPtr members. Native types can hold handles to managed objects using the gcroot templated type, which wraps System::GCHandle.
The Microsoft C++/CLI compiler is capable of generating either pure MSIL or a mixture of MSIL and native code, depending on whether you use /clr or /clr:pure or /clr:safe (the last restricts /clr:pure to produce only verifiable MSIL). The answers to most of your other questions depend on which of these modes it is in. For example, any MSIL it produces will run on Mono, but mixed native and MSIL won't, because it relies on internals of the Microsoft .NET runtime.
Any limitations apply only to managed types (e.g. ref class, enum class) created with C++/CLI. Native types, even when compiled to pure MSIL, have the full flexibility of the C++ language including multiple inheritance, templates, etc.
C++/CLI catches managed exception types in both native and managed code (/clr forces the /EHa compiler option).
C++/CLI provides a stack semantics syntax (declare a variable whose type doesn't include the ^ suffix meaning handle). This is possible for both local variables and members of managed types. The compiler will automatically produce calls to IDisposable::Dispose for types which implement it in all the usual places (like a C# using block for local variables, automatically create an IDisposable implementation in managed types which calls Dispose on all members).
Lambdas aren't available yet, because in the next version of Visual Studio (2010) they will be added using the syntax defined by the upcoming C++ standard.
You can't run managed code in kernel mode regardless of what compiler you use, C++/CLI changes nothing in this area.
You really have way too many points here for a single question. If you really want me to go through every point I will, but it's going to be a series of blog entries and I'll just leave a link here.
Like a lot of places my workplace has legacy code floating around along with more modern applications. For example we have a server application that still uses the Microsoft Fortran77 compiler. The less old parts of the application are written for the Visual Studio 6 C compiler and lately there have been runours of writing some new libraries with VS .Net 2008 C++. The programs/libraries have a number of different mechanisms to consume/communicate each other including static linking, shared memory (Windows memory mapped files), name pipes and TCP sockets.
What's to stop a C# application from being able to use any old library such as one of the Fortran77 ones written in a procedural langauge?
If my C# application understood the file format of a Fortan77 or C library and was able to locate the procedure call it wanted could it marshal the managed objects across, call the procedure and unmarshal the result?
If I copied a .so library file from Linux to Windows and my C# application understood the file format could it call functions from that library?
I think the answers are to do with the various Fortran, C etc. runtimes that are needed to initialise each library/program. If that's so then at a fundamental level are those runtimes the broadly similar to the CLR (realising they have different features such as memory management etc. etc. in the CLR's case)?
Edit:
To put my question another way. If an alien dropped in and gave me a binary library file and a file format specification could I use it from C#?
If the DLLs are valid DLLs and the functions exported use well-known calling conventions, then there should be no problem as long as you get the method signature in .NET right i.e: correct argument types and return type. CLR doesn't (and can't) care what language was the library written in.
As for the Linux shared libraries, if you have the sources of the libraries, it should be possible to compile them for windows using either Cygwin or MiniGW.
I don't know about Fortan77 or .so library from Linux, but I do know that you can use PInvoike with C libraries for method calls. Also you may want to look at the unsafe keyword in C# for the shared memory applications. It allows you to drop out of memory management, which may be what you need. Named Pipes and TCP sockets can be done from the System.Net namespace.
Basically everything you have said can be done. I don't know how hard or easy it will be to accomplish, but you should be able to access all these native apps from your C# application.
You can also create a C++/CLI DLL (/CLR option when compiling) which will allow you to write both in managed and unmanaged code. This allows you to do just about anything you could do in native C++, and also interact with .NET components. I am doing something like this to bridge an old C application with a C# DLL by having the C++/CLI dll essentially sitting between them.