{"id":33,"date":"2013-07-26T11:20:35","date_gmt":"2013-07-26T11:20:35","guid":{"rendered":"https:\/\/praveenkatiyar.wordpress.com\/?p=33"},"modified":"2013-07-26T11:20:35","modified_gmt":"2013-07-26T11:20:35","slug":"marshaling-introduction-1-of-n","status":"publish","type":"post","link":"https:\/\/praveenkatiyar.in\/blog\/index.php\/2013\/07\/26\/marshaling-introduction-1-of-n\/","title":{"rendered":"Marshaling Introduction (1 of N)"},"content":{"rendered":"<h3><a name=\"_Toc361061655\">What is Marshaling?<\/a><\/h3>\n<p><strong>Marshaling <\/strong>(similar to serialization) is the process of transforming the memory representation of an object to a data format suitable for storage or transmission. It is typically used when data must be moved between different parts of a computer program or from one program to another.<\/p>\n<p>in the .NET scenario, Marshaling is the process of creating a bridge between managed code and unmanaged code; it is the homer that carries messages from the managed to the unmanaged environment and reverse. It is one of the core services offered by the CLR (Common Language Runtime.) Because much of the types in unmanaged environment do not have counterparts in managed environment, you need to create conversion routines that convert the managed types into unmanaged and vice versa; and that is the marshaling process. As a refresher, we call .NET code \u201cmanaged\u201d because it is controlled (managed) by the CLR. Other code that is not controlled by the CLR is called <\/p>\n<h3><a name=\"_Toc361061657\">When we need Marshaling<\/a><\/h3>\n<p>You already know that there is no such compatibility between managed and unmanaged environments. In other words, .NET does not contain such the types HRESULT, DWORD, and HANDLE that exist in the realm of unmanaged code. Therefore, you need to find a .NET substitute or create your own if needed. That is what called marshaling.<\/p>\n<p>An example is the unmanaged DWORD; it is an unsigned 32-bit integer, so we can marshal it in .NET as System.UInt32. Therefore, System.UInt32 is a substitute for the unmanaged DWORD.<\/p>\n<p>Marshaling comes handy when you are working with unmanaged code, whether you are working with Windows API or COM components. It helps you interoperating (i.e. working) correctly with these environments by providing a way to share data between the two environments.&#160; <\/p>\n<p><a href=\"http:\/\/praveenkatiyar.wordpress.com\/wp-content\/uploads\/2013\/07\/image.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"background-image:none;padding-top:0;padding-left:0;margin:0;display:inline;padding-right:0;border-width:0;\" border=\"0\" alt=\"image\" src=\"http:\/\/praveenkatiyar.wordpress.com\/wp-content\/uploads\/2013\/07\/image_thumb.png\" width=\"414\" height=\"125\" \/><\/a><\/p>\n<h3>Interop Marshaling<\/h3>\n<p>Interop marshaling governs how data is passed in method arguments and return values between managed and unmanaged memory during calls. Interop marshaling is a run-time activity performed by the common language runtime&#8217;s marshaling service. <\/p>\n<p>Most data types have common representations in both managed and unmanaged memory. The interop marshaler handles these types for you. Other types can be ambiguous or not represented at all in managed memory. <\/p>\n<p>An ambiguous type can have either multiple unmanaged representations that map to a single managed type, or missing type information, such as the size of an array. For ambiguous types, the marshaler provides a default representation and alternative representations where multiple representations exist. You can supply explicit instructions to the marshaler on how it is to marshal an ambiguous type. <\/p>\n<h3>Default Marshaling<\/h3>\n<ul>\n<li><strong>Platform invoke,<\/strong> which enables managed code to call functions exported from an unmanaged library. <\/li>\n<li><strong>COM interop,<\/strong> which enables managed code to interact with COM objects through interfaces. <\/li>\n<\/ul>\n<h3>Marshaling data with platform Invoke (PInvoke)<\/h3>\n<p>To call functions exported from an unmanaged library, a .NET Framework application requires a function prototype in managed code that represents the unmanaged function. To create a prototype that enables platform invoke to marshal data correctly, you must do the following: <\/p>\n<ul>\n<li>\n<div align=\"justify\">Apply the <strong>DLLImportAttribute<\/strong> attribute to the static function or method in managed code.<\/div>\n<\/li>\n<li>Substitute managed data types for unmanaged data types. <\/li>\n<\/ul>\n<p>You can use the documentation supplied with an unmanaged function <strong>to construct an equivalent managed prototype<\/strong> by applying the attribute with its optional fields and substituting managed data types for unmanaged types. <\/p>\n<h4>Memory Management<\/h4>\n<p>The interop marshaler always attempts to free memory allocated by unmanaged code. This behavior complies with COM memory management rules, but differs from the rules that govern native C++. <\/p>\n<p>Confusion can arise if you anticipate native C++ behavior (no memory freeing) when using platform invoke, which automatically frees memory for pointers.&#160; <\/p>\n<p>see the following example<\/p>\n<p><strong>BSTR MyMethod (BSTR b) <\/strong><\/p>\n<p><strong>{<\/strong><\/p>\n<p><strong>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return b; <\/strong><\/p>\n<p><strong>} <\/strong><\/p>\n<p>However, if you define the method as a platform invoke prototype, replace each <b>BSTR<\/b> type with a <strong>String<\/strong> type, and call <code>Method<\/code>, the common language runtime attempts to free <code>variable<strong> b<\/strong><\/code> twice in the above example. You can change the marshaling behavior by using <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.intptr(v=vs.71).aspx\">IntPtr<\/a> types rather than <b>String<\/b> types.<\/p>\n<p>The runtime always uses the <b>CoTaskMemFree<\/b> method to free memory. If the memory you are working with was not allocated with the <b>CoTaskMemAlloc<\/b> method, you must use an <b>IntPtr<\/b> and free the memory manually using the appropriate method. Similarly, you can avoid automatic memory freeing in situations where memory should never be freed.<\/p>\n<h4>Directional attribute<\/h4>\n<p>Directional attributes are optional. You apply them to method parameters when you want to alter the default behavior of the marshaler. If you omit directional attributes from a method parameter, the marshaler determines the directional flow based on the type of the parameter (<strong>value or reference<\/strong>) and its modifiers, if any.<\/p>\n<p>Some languages provide keywords that enable you to modify the directional flow of method parameters. The following table lists the direction-related keywords provided by Visual Basic .NET and C# and shows the equivalent IDL interface attribute.<\/p>\n<h5>Default marshaling of method arguments to unmanaged code<\/h5>\n<p><b>ByRef<\/b>, <b>ref<\/b>, and <b>out<\/b> parameter modifiers cause method arguments to be marshaled by reference rather than by value. Method arguments passed by value are marshaled to unmanaged code as values on the stack; arguments passed by reference are marshaled as pointers on the stack. The figure below shows the default marshaling behavior of value types and reference types with parameter modifiers.<\/p>\n<p><a href=\"http:\/\/praveenkatiyar.wordpress.com\/wp-content\/uploads\/2013\/07\/image1.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"background-image:none;padding-top:0;padding-left:0;margin:0;display:inline;padding-right:0;border-width:0;\" border=\"0\" alt=\"image\" src=\"http:\/\/praveenkatiyar.wordpress.com\/wp-content\/uploads\/2013\/07\/image_thumb1.png\" width=\"583\" height=\"129\" \/><\/a><\/p>\n<p>By default, reference types (classes, arrays, strings, and interfaces) passed by value are marshaled as <strong>In parameters<\/strong> for performance reasons. You do not see changes to these types unless you apply <b>InAttribute<\/b> and <b>OutAttribute<\/b> (or just <b>OutAttribute<\/b>) to the method parameter. <strong>The <\/strong><a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.text.stringbuilder(v=vs.71).aspx\"><strong>StringBuilder<\/strong><\/a><strong> class<\/strong>, which is an exception to this rule, <strong>is marshaled as an In\/Out<\/strong> parameter.<\/p>\n<p>The interop marshaler guarantees the following behavior with regard to directional attributes: <\/p>\n<ul>\n<li>The interop marshaler <strong>never generates a write operation to an In parameter passed from unmanaged code<\/strong>. Thus, unmanaged code can safely pass a pointer to a read-only page, or a pointer to concurrently accessed data. <\/li>\n<li>When the copied object contains an allocated object, such as a <b>BSTR<\/b>, the marshaler always executes the correct sequence of allocations and destructions demanded by the In\/Out settings. <\/li>\n<\/ul>\n<h3>Default Marshaling <\/h3>\n<p>To call functions exported from an unmanaged library, a .NET Framework application requires <\/p>\n<h4>Blittable Types<\/h4>\n<p>Most data types have a common representation in both managed and unmanaged memory and <strong>do not require special handling by the<\/strong> <strong>interop marshaler<\/strong>. These types are called <strong>blittable<\/strong> types <strong>because they do not require conversion when passed between managed and unmanaged code.<\/strong><\/p>\n<ul>\n<li>System.Byte <\/li>\n<li>System.SByte <\/li>\n<li>System.Int16 <\/li>\n<li>System.UInt16 <\/li>\n<li>System.Int32 <\/li>\n<li>System.UInt32 <\/li>\n<li>System.Int64 <\/li>\n<li>System.IntPtr <\/li>\n<li>System.UIntPtr <\/li>\n<li><strong>One-dimensional arrays of blittable types<\/strong>, such as an <strong>array of integers<\/strong> <\/li>\n<li>Formatted value types that contain only blittable types (and classes if they are marshaled as formatted types). <\/li>\n<\/ul>\n<p>The following table lists <strong>non-blittable<\/strong> types from the <strong>System<\/strong> namespace. <strong>Delegates<\/strong>, which are data structures that refer to a static method or to a class instance, are also non-blittable.<\/p>\n<ul>\n<li>System.Array <\/li>\n<li>System.Boolean <\/li>\n<li>System.Char <\/li>\n<li>System.Object <\/li>\n<li>System.Mdarray <\/li>\n<li>System.String <\/li>\n<li>System.Valuetype <\/li>\n<li>System.SzArray <\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>What is Marshaling? Marshaling (similar to serialization) is the process of transforming the memory representation of an object to a data format suitable for storage or transmission. It is typically used when data must be moved between different parts of a computer program or from one program to another. in the .NET scenario, Marshaling is&hellip; <a class=\"more-link\" href=\"https:\/\/praveenkatiyar.in\/blog\/index.php\/2013\/07\/26\/marshaling-introduction-1-of-n\/\">Continue reading <span class=\"screen-reader-text\">Marshaling Introduction (1 of N)<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,3,12],"tags":[33],"class_list":["post-33","post","type-post","status-publish","format-standard","hentry","category-net","category-codeproject","category-soa","tag-wcf","entry"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/posts\/33","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=33"}],"version-history":[{"count":0,"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/posts\/33\/revisions"}],"wp:attachment":[{"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=33"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=33"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/praveenkatiyar.in\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=33"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}