Click here to Skip to main content
15,881,281 members
Articles / Programming Languages / C#

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 256K   1.6K   58  
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.
// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#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;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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