Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

Mixing Managed and Unmanaged code

Rate me:
Please Sign up or sign in to vote.
4.29/5 (14 votes)
30 May 20013 min read 255.8K   1.6K   58   18
C++ managed code introduced us a new string type, namely System.String. You can imagine though, that some conversion functions are needed to work with this new string type when mixing managed and unmanaged code in your project.

Abstract

C++ managed code introduced us a new string type, namely System.String. You can imagine though, that some conversion functions are needed to work with this new string type when mixing managed and unmanaged code in your project.

Introduction

Managed code runs under the .NET runtime Execution Engine, which gives you the advantage of garbage collection, JIT, etc. Currently, as a programmer you can choose between C#, C++ managed extensions and VB.NET to write your managed code (there are also .NET versions of FORTRAN and COBOL, however, these are not widely available at the time of writing - ed. ). However, in some cases, you do want to mix your managed code with unmanaged code : either you still want to continue using your current source code base and plug it in .NET, maybe you want to build .NET interfaces around your existing code, or you decide to write some routines unmanaged because of performance issues.

Mixing managed and unmanaged code

/CLR

If you want to mix managed and unmanaged code in the same sources, your code should be compiled with the /CLR compiler option. This means that - by default – all your functions are managed. For compilation: members of managed classes as well as functions who use managed data types only compile as managed.

#pragma managed
#pragma unmanaged

Using the managed and unmanaged pragmas enables function-level control for compiling functions managed or unmanaged.

Strings

Unmanaged C++ applications use string types composed of ASCII/UNICODE characters ( char* , wchar_t* , std::string , CString ). Managed objects can’t handle these types, therefore a new string type System.String is introduced.

In the MSDN documentation you will find that :

"Regular C++ wide-character string literals (prefixed by L) and managed string literals (prefixed by S) can be used interchangeably where String types are expected. However, the reverse is not true. Managed string literals can not be used where C++ string types are expected."

So, in functions where a char* argument is expected, a conversion from String to char* will need to happen. In the System::Runtime::InteropServices namespace (assembly: mscorlib.dll ), a Marshal class is available to do such conversions. This Marshal class takes care of unmanaged memory allocation, copying unmanaged memory blocks, and managed to unmanaged type conversions.

For example, consider this piece of code (written in C++) :

#pragma unmanaged

#include "Windows.h"

class CUnmanagedClass
{
public:
	void ShowMessageBox(char* szMessage)
	{
		::MessageBox(NULL, szMessage , "CUnmanagedClass", MB_OK);
	}
};

#pragma managed

#using <mscorlib.dll>

using namespace System;
using namespace System::Runtime::InteropServices;

__gc class CManagedClass
{
public:
	void ShowMessage(System::String* strMessage)
	{
     	System::Console::WriteLine(strMessage);
	}
};

int main(void) 
{
	String* strMessage = S"Hello world";
	
	CManagedClass* pCManagedClass = new CManagedClass();
	pCManagedClass->ShowMessage(strMessage);
	
	char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage);
	CUnmanagedClass cUnmanagedClass; cUnmanagedClass.ShowMessageBox(szMessage);
	Marshal::FreeHGlobal((int)szMessage);
	
	return 0;
}

The unmanaged class CUnManagedClass , contains one method which expects a char* as argument. If you a want to call that method ( ShowMessageBox ) from a managed piece of code, you would need to do a conversion like this:

char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage);

And freeing the memory again with FreeHGlobal:

Marshal::FreeHGlobal((int)szMessage);

In the sample, I used StringToHGlobalAnsi to do the conversion. StringToHGlobalAnsi copies the contents of a managed String object into native heap and converts it into ASCII. The result of StringToHGlobalAnsi is an integer value, which should be cast to a char pointer.

Data marshaling when making calls between managed and unmanaged code when using P/Invoke in C#

In C#, unmanaged methods are called by using the Runtime's Platform Invocation Service (P/Invoke). Your data also needs to be marshaled then : the marshalling attributes can be specified in the dllimport statement. Consider the following lines of code (written in C#):

[DllImport("user32.dll")] 
public static extern int MessageBoxA(int h,  
            [MarshalAs(UnmanagedType.LPStr)]string m,  
            [MarshalAs(UnmanagedType.LPStr)]string c,  
            int type); 
 
public static int Main(string args [])
{
	MessageBoxA(0, "Hello World!", "My Message Box", 0); 
    return 0; 
} 

The function MessageBoxA expects 2 char pointer arguments (these are non-supported types in a managed environment). By specifying the attribute MarshalAs(UnmanagedType.LPStr) , the runtime's marshaling service will take care of transferring the data of our strings from the managed environment to the unmanaged environment.

Conclusion

Mixing managed and unmanaged code can be very powerful, and it gives us – programmers - a lot more freedom to decide on how to code. However, we should be aware that mixing these technologies introduces some extra difficulties and should be taken care off from the beginning, when starting to design your .NET applications.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Belgium Belgium
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralC2440 Error when convert to char * Pin
kosmas26-Apr-07 20:26
kosmas26-Apr-07 20:26 
GeneralRe: C2440 Error when convert to char * Pin
Vertexwahn2-May-07 21:01
Vertexwahn2-May-07 21:01 
GeneralRe: C2440 Error when convert to char * Pin
vukovicg10-Jul-11 20:53
vukovicg10-Jul-11 20:53 
GeneralConvert a Managed class to an Unmanaged type Pin
Trankil31-May-05 7:15
Trankil31-May-05 7:15 
GeneralRe: Convert a Managed class to an Unmanaged type Pin
Bhagirathi Lakshmivarahan19-Jul-07 7:28
Bhagirathi Lakshmivarahan19-Jul-07 7:28 
Generalconvert std::string to System::String* Pin
Emiliano30-Mar-05 12:11
Emiliano30-Mar-05 12:11 
GeneralRe: convert std::string to System::String* Pin
__alias23-Aug-06 9:42
__alias23-Aug-06 9:42 
QuestionHow can I convert a Gdiplus.Graphic* to System.Drawing.Graphics*? Pin
Anonymous24-Jan-05 20:10
Anonymous24-Jan-05 20:10 
GeneralError C3633 Pin
bamoo18-Jan-05 8:34
bamoo18-Jan-05 8:34 
GeneralUn managed CString to managed String* Pin
haranath5-May-03 6:46
haranath5-May-03 6:46 
Generalsmall question Pin
Anonymous26-Jul-02 10:46
Anonymous26-Jul-02 10:46 
GeneralOne small problem... Pin
20-Jun-02 6:47
suss20-Jun-02 6:47 
GeneralRe: One small problem... Pin
Anonymous24-Jul-02 10:52
Anonymous24-Jul-02 10:52 
GeneralRe: One small problem... Pin
Anonymous13-Oct-02 14:33
Anonymous13-Oct-02 14:33 
GeneralRe: One small problem... Pin
ratty15-Nov-02 9:15
ratty15-Nov-02 9:15 
GeneralRe: One small problem... Pin
ratty15-Nov-02 9:16
ratty15-Nov-02 9:16 
GeneralRe: One small problem... Pin
boaza25-Jan-07 2:34
boaza25-Jan-07 2:34 
GeneralRe: One small problem... Pin
EntilzhaFini24-Sep-09 5:08
EntilzhaFini24-Sep-09 5:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.