Managed and Un-Managed Code in .NET

download Managed and Un-Managed Code in .NET

of 7

Transcript of Managed and Un-Managed Code in .NET

  • 8/13/2019 Managed and Un-Managed Code in .NET

    1/7

    Visual Studio.NET

    Best Articles

    Managed and Un-Managed Code in .NET

    Managed Code

    Code that is executed by the CLR is called managed code. Managed code provides information(i.e., metadata) to allow the CLR to locate methods encoded in assembly modules, store and retrievesecurity information, handle exceptions, and wal the program stac. Managed code can access both

    managed data and unmanaged data. Managed data!Memory that is allocated and released by theCLR using "arbage Collection. Managed data can only be accessed by managed code

    #ou can thin of the runtime as an agent that manages code at execution time, providing coreservices such as memory management, thread management, and Remoting, while also enforcing stricttype safety in the code. $he concept of code management is a fundamental principle of the runtime.

    Un-Managed Code

    Code that does not target the common language runtime is nown as unmanaged code inother words code that runs outside the runtime is called unmanaged code.

    $he Microsoft .%&$ 'ramewor promotes interaction with CM components, CM services,

    external type libraries, and many operating system services. *ata types, method signatures, anderror+handling mechanisms vary between managed and unmanaged obect models. $o simplifyinteroperation between .%&$ 'ramewor components and unmanaged code and to ease the migrationpath, the common language runtime conceals from both clients and servers the differences in these

    obect models.

    Calling Unmanaged Code from .Net

    -las, its impossible to do everything within the .%et framewor. $o solve your programming problem,you probably need to call code thats provided as a part of a *LL. /eres how to achieve that withoutmaing some silly mistaes.

    *espite the breadth and depth of the .%et 'ramewor, it cannot do everything. $here are times when

    you need to do something that is not covered by the 'ramewor. 0n my experience, this situationcomes up in two contexts. ne is when there is some capability that you now is part of the 1indows-20 but is not yet in the .%et 'ramewor. $he other is when you are programming an external devicewhose drivers are written for the non+. %et programmer. $he result is the same3 in both cases, yourprogram will need to call unmanaged code. More specifically, it needs to call code that is provided aspart of a dynamic lin library or *LL (a 1indows *LL in the first case, a manufacturer+provided *LL inthe second).

    1indows and device *LLs are almost always written in C. $his means that you, the .%et programmer,face two challenges3

    /ow do you call functions in an unmanaged code *LL from your managed code .%et program4

    /ow do you map the C51indows data types passed to and returned from the *LL functions to

    the Common Language Runtime (CLR) types used in .%et4

    $hese 6uestions fall under the general area of interoperability(interop for short). 0n .%et, or morespecifically in the CLR, the most important interop tool is called 2latform 0nvoe (or 2+0nvoe). 2+0nvoe is a service that permits managed code to call unmanaged functions that are implemented in*LLs. 0n the .%et documentation this is referred to as consumingunmanaged *LLs. Lets tae a looat how this is done.

    Identifying the !! "unction

    7efore your managed code can call a *LL function, it must now the name of the function and where it

    is located ! in other words, in which *LL. #ou do this with the DllImporteyword. $his is in the

    Ravi Varma Thumati Page 1 11/19/2013

  • 8/13/2019 Managed and Un-Managed Code in .NET

    2/7

    Visual Studio.NET

    Best Articles

    System.Runtime.InteropServices namespace. 'or an example, 0 will use the 1indows Beep()function, which has the following declaration (in C)3

    7L 7eep( *1R* dw're6,55 're6uency

    *1R* dw*uration

    55*uration in milliseconds

    89

    $o mae this function accessible in your managed code, you would write the DllImportstatement liethis3:*ll0mport(;.dll;)? static extern 7oolean 7eep(

    @0nt=> fre6uency, @0nt=> duration)9

    *ont worry about the data types for now9 0ll get to them soon. 7ut with this DllImportstatement inyour managed code, you can call the 7eep function lie any other function37eep(ABBB, ABB)9

    -s is often the case, the return value of 1indows -20 functions is ignored, because it does not provide

    any useful information. (*ll0mport has optional parameters that are needed in some situations. #oucan learn about these in the .%et online documentation.)

    7efore you can use functions in a *LL, you must now about them. 1here can you get thisinformation4 'or the 1indows -20, 0 recommend one of the several reference boos that are available.$hese boos provide information about using each -20 function including its arguments and returntype and the *LL it is contained in ($he 1indows -20 is contained in a small set of *LLs that are partof the 1indows installation). 'or third party *LLs, the product documentation should contain thisinformation.

    -s 0 mentioned, 1indows *LLs are part of the 1indows installation and are found by the programwithout any special effort on your part. %or do you have to include the *LL files in your distributionpacage. 'or third party *LLs, its best to put them in the application folder where they will be foundby the *ll0mport service. 0n this case, you do have to include the *LLs in any distribution pacage you

    may create.

    Ma##ing ata Ty#es

    ne of the tass performed by the 2+0nvoe service is to marshal data across themanaged5unmanaged code boundary. $he data types used by *LL functions rarely have the samenames as the CLR data types, so it is incumbent on the programmer to determine the correct CLRdata types to use. $he table below lists the commonly use data types in unmanaged C functions and inthe 1indows -20 along with the CLR e6uivalents.

    Unmanaged$indo%s A&I ty#es

    Unmanaged Clanguage ty#es

    C!' ty#e

    /-%*L& voidD 0nt2tr

    7#$& unsigned char 7yte

    E/R$ short 0ntAF

    1R* unsigned short @0ntAF

    0%$, L%" int, long 0nt=>

    7L int, long 0nt=> or 7oolean

    @0%$ unsigned int @0nt=>

    *1R*, @L%" unsigned long @0nt=>

    C/-R char Char

    Ravi Varma Thumati Page 2 11/19/2013

  • 8/13/2019 Managed and Un-Managed Code in .NET

    3/7

    Visual Studio.NET

    Best Articles

    L2E$R, L2CE$R,L21E$R, L2C1E$R

    charD, wcharGtD Etring or Etring7uilder

    'L-$ float Eingle

    *@7L& double *ouble

    0f those asteriss have you looing for a footnote, perhaps you are not familiar with C programming.$he asteris is used to designate a pointer, a type of data storage in which a variable does not containthe data, per se, but rather contains the memory address of the data. #ou neednt be concerned withthe details of pointers as long as you use the appropriate CLR type.

    #ou can see now how 0 came up with the DllImportdeclaration for the Beep()function. 'or the 7Lreturn value, 0 used the CLR type 7oolean, and for the two *1R* arguments 0 used the CLR type

    UInt32. 1ith the correct data types in place, the 2+0nvoe data marshalling wors properly, ensuringthat the *LL function is passed the correct argument types and that the return value, if used by thecalling program, is correct.

    $ra##ing the !! "unctions

    0f you are going to use unmanaged *LL functions in your program, its a good idea to wrap them in aclass. -side from the advantages of modularity and reusability, providing a class wrapper is advisable

    because consuming *LL functions can in some cases be prone to errors. &ncapsulating the *LLdeclarations and calls maes your ob easier when it comes time to debug whatever problems comeup. $he general approach is to declare (using *ll0mport) the function in the class and then create apublic method that calls the *LL. &xception handling can be performed within the class. #ou cancreate a separate class for each *LL function or, perhaps more conveniently, create a single class thatwraps a set of perhaps related *LL functions.

    Lets loo at an example. $he class shown here encapsulates a single 1indows -20 function, Beep().$o add other functions, simply add a DllImportstatement and a public method for each one. -dd theclass to any proect that needs to call the -20 functions.

    using Eystem9using Eystem.Runtime.0nteropEervices9

    namespace 1in-20

    Hpublic class 1indows-20

    H :*ll0mport(;.dll;)? static extern 7oolean 7eep(@0nt=> duration, @0nt=> fre6uency)9

    public void 1in7eep(@0nt=> duration, @0nt=> fre6uency) H 7eep(duration, fre6uency)9 8 88

    $hen in your program, calling the function is a simple matter. #ou must import the classs namespace3

    using 1in-209$hen instantiate the class31indows-20 w-20 I new 1indows-20()9...and finally call the appropriate method3w-20.1in7eep(ABBB, ABB)9

    Managed code provides many advantages. 1hen its possible to create an entire application inmanaged code it is almost always the best way to go. $he world is still full of unmanaged code,however, and sometimes the .%et programmer will need to mae use of it.

    Ravi Varma Thumati Page 3 11/19/2013

  • 8/13/2019 Managed and Un-Managed Code in .NET

    4/7

    Visual Studio.NET

    Best Articles

    Using Managed Components from Unmanaged Codeifferences Bet%een .NET "rame%or( and C)M "rame%or(

    $he .%&$ framewor obect model and its worings are different from Component bect Model (CM)and its worings. 'or example, clients of .%&$ components dont have to worry about the lifetime ofthe obect. Common Language Runtime (CLR) manages things for them. 0n contrast, clients of CMobects must tae care of the lifetime of the obect. Eimilarly, .%&$ obects live in the memory space

    that is managed by CLR. CLR can move obects around in the memory for performance reasons andupdate the references of obects accordingly, but CM obect clients have the actual address of theobect and depend on the obect to stay on the same memory location.

    Eimilarly, .%&$ runtime provides many new features and constructs to managed components. 'orexample, .%&$ components can have parameteriJed constructors, functions of the components canhave accessibility attributes (lie public, protected, internal, and others) associated with them, andcomponents can also have static methods. -part from these features, there are many others. $heseinclude ones that are not accessible to CM clients because standard implementation of CM does notrecogniJe these features. $herefore .%&$ runtime must put something in between the two, .%&$ serverand CM client, to act as mediator.

    The .NET and C)M Mediator

    .%&$ runtime provides CM 0nteroperability wrappers for overcoming the differences between .%&$and CM environments. 'or example, runtime creates an instance of CM Callable 1rapper (CC1)when a CM client accesses a .%&$ component. 0n the same way, an instance of Runtime Callable1rapper (RC1) is created when a .%&$ client accesses a CM component. $hese wrappers abstractthe differences and provide the seamless integration between the two environments. $he followingdiagram illustrates CC1 and RC1.

    !et*s o Something &ractical

    'or demonstration purposes, 0 have created a .%&$ component in CK named CManagedEerver. $hiscomponent is in the ManagedEerver assembly. 'or client side, 0 have created a isual 7asic (7) F.B+based client that uses the services of our managed server.

    Ste# +'irst, we create the managed server. $he following code for CManagedEerver is very simple andcontains a single method named ;Eay/ello.;

    using Eystem9namespace ManagedEerver

    Ravi Varma Thumati Page 4 11/19/2013

  • 8/13/2019 Managed and Un-Managed Code in .NET

    5/7

    Visual Studio.NET

    Best Articles

    H public class CManagedEerver H public CManagedEerver() H8 public string Eay/ello(string rGstr%ame)

    Hstring str 9str I ;/ello ; rGstr%ame 9return str 98

    88

    'or compilation and creation of ManagedEerver assembly, use the following command3

    csc 5out3ManagedEerver.dll 5target3library ManagedEerver.cspause

    $his command will create the ManagedEerver.dll file. $his is our managed server.

    Ste# ,Etandard CM implementation relies on the 1indows registry for looing up the information related toCM components, lie CLE0*, 0nterface 0*s, the path of the components housing (*LL5exe), thecomponent threading model, etc. .%&$ framewor does not depend on the registry and uses metadatafor this information. $herefore, we have to generate the CM+compatible registry entries for ourmanaged server so that the CM runtime could instantiate our server. Lie tlbimp.exe, there is a toolnamed regasm.exe. $his tool reads the metadata information within an assembly and adds the

    corresponding CM+compatible registry entries. Classes in the assembly are not CM creatable untilthey are actually registered in the 1indows registry.Regasm.exe tool can also generate the CM type library for our manager server. 1e will referencethis type library in 7 F.B client.$he following command can be used for creating the registry entries and type library for our managedserver3

    regasm ManagedEerver.dll 5tlbpause

    'ollowing is the output that will be generated after successful execution of the above command3

    Ravi Varma Thumati Page 5 11/19/2013

  • 8/13/2019 Managed and Un-Managed Code in .NET

    6/7

    Visual Studio.NET

    Best Articles

    -t this point, standard CM registry entries will have been created. Loo at the following figure, thisshows the registry entries on my 2C3

    Ste#

    %ow we will create the client of our managed server. 0 have created a simple client.Etep > created a tlb so we will reference it in the 7 client. $he following figure shows theManagedEerver tlb listed in the ;References; dialog.

    $he following is the code that creates the obect and calls its Eay/ello Method.

    2rivate Eub cmd-ccessManagedComponentGClic()

    Ravi Varma Thumati Page 6 11/19/2013

  • 8/13/2019 Managed and Un-Managed Code in .NET

    7/7

    Visual Studio.NET

    Best Articles

    *im obEerver -s %ew ManagedEerver.CManagedEerver Msg7ox obEerver.Eay/ello(;A Eeconds reader;) Eet obEerver I %othing&nd Eub

    $he above code is very simple and CM 0nteroperability wrappers have abstracted all the complexitiesof accessing .%&$ components.Running the @nmanagedClient.exe and pressing the ;-ccess managed component; button, willproduce the following output3

    Conclusion

    $his is what we need to do to access .%&$ components from unmanaged code. 0f you want to develop

    some of your application components in .%&$, you should consider that many of the features of .%&$components are not exposed to CM clients. $his will re6uire some design+time decisions and mayaffect the way you design your obect hierarchies (because inheritance hierarchy of .%&$ componentsis flattened for CM clients).ne more thing, currently .%&$ components are accessible to CM clients only. .%&$ components

    cannot be accessed from 1in=> *LLs or executables. 0 am not sure whether Microsoft will incorporatethis in future.

    ey #oint to remem/er0

    Managed code Means0 -

    o Code that is executed by the CLR.

    o Code that targets the common language runtime, the foundation of the .NET Framework, is

    known as managed code.

    o anaged code su!!lies the metadata necessary for the CLR to !ro"ide ser"ices such as

    memory management, cross#language integration, code access security, and automatic lifetime

    control of ob$ects. %ll code based on &L executes as managed code.

    o Code that executes under the CL& execution en"ironment.

    Unmanaged codeeans' #

    o &t is com!iled to machine code and therefore executed by the () directly.

    o &t therefore has the ability to do damaging*!owerful things anaged code does not.

    Ravi Varma Thumati Page 7 11/19/2013