<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US"><title type="html">Devin Jenson's WebLog</title><subtitle type="html">That One Guy</subtitle><id>http://blogs.msdn.com/devinj/atom.xml</id><link rel="alternate" type="text/html" href="http://blogs.msdn.com/devinj/default.aspx" /><link rel="self" type="application/atom+xml" href="http://blogs.msdn.com/devinj/atom.xml" /><generator uri="http://communityserver.org" version="2.1.61025.2">Community Server</generator><updated>2005-07-11T20:34:00Z</updated><entry><title>The Danger of Marshal.StructureToPtr</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/devinj/archive/2005/08/13/451195.aspx" /><id>http://blogs.msdn.com/devinj/archive/2005/08/13/451195.aspx</id><published>2005-08-13T11:10:00Z</published><updated>2005-08-13T11:10:00Z</updated><content type="html">&lt;P&gt;&lt;FONT face=Verdana size=2&gt;Pop Quiz! Is the following code &lt;I&gt;secure&lt;/I&gt;:&lt;/P&gt;
&lt;BLOCKQUOTE style="PADDING-RIGHT: 5px; PADDING-LEFT: 5px; BACKGROUND: #fff; BORDER-LEFT: #47f 3px solid; FONT-STYLE: normal"&gt;&lt;PRE&gt;&lt;FONT face="Courier New" size=2&gt;
&lt;FONT color=#0000ff&gt;public static unsafe&lt;/FONT&gt; &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt; WriteListToNewNativeBuffer&amp;lt;T&amp;gt;(
    &lt;FONT color=#008080&gt;List&lt;/FONT&gt;&amp;lt;T&amp;gt; list)
{
    &lt;FONT color=#0000ff&gt;if&lt;/FONT&gt; (list == &lt;FONT color=#0000ff&gt;null&lt;/FONT&gt;)
    {
        &lt;FONT color=#0000ff&gt;throw new&lt;/FONT&gt; &lt;FONT color=#008080&gt;ArgumentNullException&lt;/FONT&gt;(&lt;FONT color=#800000&gt;"list"&lt;/FONT&gt;);
    }

    &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt; nativeBuffer = &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt;.Zero;
    &lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; elementSize = &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.SizeOf(&lt;FONT color=#0000ff&gt;typeof&lt;/FONT&gt;(T));

    &lt;FONT color=#0000ff&gt;try&lt;/FONT&gt;
    {
        nativeBuffer = &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.AllocCoTaskMem(list.Count * elementSize);
        &lt;FONT color=#008080&gt;Byte&lt;/FONT&gt;* bytePtr = (&lt;FONT color=#008080&gt;Byte&lt;/FONT&gt;*)nativeBuffer.ToPointer();

        &lt;FONT color=#0000ff&gt;foreach&lt;/FONT&gt; (T element &lt;FONT color=#0000ff&gt;in&lt;/FONT&gt; list)
        {
            &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.StructureToPtr(element, &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt;(bytePtr), &lt;FONT color=#0000ff&gt;false&lt;/FONT&gt;);
            bytePtr += elementSize;
        }

        &lt;FONT color=#0000ff&gt;return&lt;/FONT&gt; nativeBuffer;
    }

    &lt;FONT color=#0000ff&gt;catch&lt;/FONT&gt;
    {
        &lt;FONT color=#0000ff&gt;if&lt;/FONT&gt; (nativeBuffer != &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt;.Zero)
        {
            &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.FreeCoTaskMem(nativeBuffer);
        }

        &lt;FONT color=#0000ff&gt;throw&lt;/FONT&gt;;
    }
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face=Verdana size=2&gt;Assuming the caller is properly freeing up memory, and assuming I didn't mess up the blog translation, it sure looks like all bases are covered. As you expected me to conclude, this code is insecure -- it can lead to a &lt;B&gt;buffer overflow&lt;/B&gt;. Take this program which demonstrates the problem:&lt;/FONT&gt;&lt;/P&gt;
&lt;BLOCKQUOTE style="PADDING-RIGHT: 5px; PADDING-LEFT: 5px; BACKGROUND: #fff; BORDER-LEFT: #47f 3px solid; FONT-STYLE: normal"&gt;&lt;PRE&gt;&lt;FONT face="Courier New" size=2&gt;
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System;
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System.Collections.Generic;
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System.Runtime.InteropServices;



&lt;FONT color=#0000ff&gt;class&lt;/FONT&gt; &lt;FONT color=#008080&gt;Program&lt;/FONT&gt;
{
    [&lt;FONT color=#008080&gt;StructLayout&lt;/FONT&gt;(&lt;FONT color=#008080&gt;LayoutKind&lt;/FONT&gt;.Sequential)]
    &lt;FONT color=#0000ff&gt;public class&lt;/FONT&gt; Base
    {
        &lt;FONT color=#0000ff&gt;public&lt;/FONT&gt; &lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; One;

        &lt;FONT color=#0000ff&gt;public&lt;/FONT&gt; Base(&lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; one)
        {
            One = one;
        }
    }

    [&lt;FONT color=#008080&gt;StructLayout&lt;/FONT&gt;(&lt;FONT color=#008080&gt;LayoutKind&lt;/FONT&gt;.Sequential)]
    &lt;FONT color=#0000ff&gt;public class&lt;/FONT&gt; &lt;FONT color=#008080&gt;Derived&lt;/FONT&gt; : &lt;FONT color=#008080&gt;Base&lt;/FONT&gt;
    {
        &lt;FONT color=#0000ff&gt;public&lt;/FONT&gt; &lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; Two;

        &lt;FONT color=#0000ff&gt;public&lt;/FONT&gt; Derived(&lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; one, &lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; two) : &lt;FONT color=#0000ff&gt;base&lt;/FONT&gt;(one)
        {
            Two = two;
        }
    }

    &lt;FONT color=#0000ff&gt;private static void&lt;/FONT&gt; Main()
    {
        &lt;FONT color=#008080&gt;List&lt;/FONT&gt;&amp;lt;&lt;FONT color=#008080&gt;Base&lt;/FONT&gt;&amp;gt; list = &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;List&lt;/FONT&gt;&amp;lt;&lt;FONT color=#008080&gt;Base&lt;/FONT&gt;&amp;gt;();
        list.Add(&lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Base&lt;/FONT&gt;(1));
        list.Add(&lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Derived&lt;/FONT&gt;(2, 3));

        &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt; nativeBuffer = WriteListToNewNativeBuffer&amp;lt;&lt;FONT color=#008080&gt;Base&lt;/FONT&gt;&amp;gt;(list);
        &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.FreeCoTaskMem(nativeBuffer);
    }
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face=Verdana size=2&gt;The root of the problem is that &lt;A href="http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemRuntimeInteropServicesMarshalClassStructureToPtrTopic.asp"&gt;Marshal.StructureToPtr&lt;/A&gt; only takes a basic &lt;A href="http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemobjectclasstopic.asp"&gt;System.Object&lt;/A&gt; parameter. Our WriteListToNewNativeBuffer library call is passing in the base type, but if the instance is actually a derived type, more data than expected will be written. In the sample above 12 bytes are written into an 8-byte buffer.&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;&lt;FONT face=Verdana size=2&gt;I couldn't tell you why 2.0 doesn't provide a generic overload (or an overload containing a &lt;A href="http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemtypeclasstopic.asp"&gt;System.Type&lt;/A&gt; parameter) to resolve this. Outside the generic environment, one can make an encapsulation class with a single field of the expected element type to "trick" the marshaler into marshaling only the base type even if the instance is derived. Unfortunately, classes with generic reference-type fields cannot be marshaled so in the sample above the only realistic solution is to fail (throw an exception) if the element instance type is not the expected type. Sure one can write each element into a size-checked buffer before copying the base size over to the destination buffer, but that is a lot of undesirable work for something which should be simple. Even that work-around won't work if the derived type is not marshalable.&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;&lt;FONT face=Verdana size=2&gt;Perhaps I overlooked a work-around, let me know if I did. :-)&lt;/FONT&gt;&lt;/P&gt;&lt;/FONT&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=451195" width="1" height="1"&gt;</content><author><name>devinj</name><uri>http://blogs.msdn.com/members/devinj.aspx</uri></author></entry><entry><title>Dynamically Writing and Executing Native Assembly in C#</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/devinj/archive/2005/07/12/438323.aspx" /><id>http://blogs.msdn.com/devinj/archive/2005/07/12/438323.aspx</id><published>2005-07-13T09:44:00Z</published><updated>2005-07-13T09:44:00Z</updated><content type="html">&lt;P&gt;&lt;FONT face=Verdana size=2&gt;Generally, executing native assembly in C# is bad because you lose all the benefits of the managed world. In the cases where it is impossible to perform something in C#, it is better to make a C++ DLL. That said, the new method &lt;A href="http://msdn2.microsoft.com/library/zdx6dyyh(en-us,vs.80).aspx"&gt;Marshal.GetDelegateForFunctionPointer()&lt;/A&gt; in the .NET Framework v2.0 opens up the possibility for dynamically writing and executing assembly code. Consider the following basic C function:&lt;/FONT&gt;&lt;/P&gt;

&lt;BLOCKQUOTE style="PADDING-RIGHT: 5px; PADDING-LEFT: 5px; BACKGROUND: #fff; BORDER-LEFT: #47f 3px solid; FONT-STYLE: normal"&gt;&lt;PRE&gt;&lt;FONT face="Courier New" size=2&gt;
&lt;FONT color=#0000ff&gt;int __declspec&lt;/FONT&gt;(&lt;FONT color=#0000ff&gt;noinline&lt;/FONT&gt;) &lt;FONT color=#0000ff&gt;__stdcall&lt;/FONT&gt; MyAdd(&lt;FONT color=#0000ff&gt;int&lt;/FONT&gt; x, &lt;FONT color=#0000ff&gt;int&lt;/FONT&gt; y)
{
    &lt;FONT color=#0000ff&gt;return&lt;/FONT&gt; x + y;
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;

&lt;P&gt;&lt;FONT face=Verdana size=2&gt;The C compiler will compile the code into assembly. Though the code which gets compiled may vary from compiler to platform, for x86 it will usually have this basic form:&lt;/FONT&gt;&lt;/P&gt;

&lt;BLOCKQUOTE style="PADDING-RIGHT: 5px; PADDING-LEFT: 5px; BACKGROUND: #fff; BORDER-LEFT: #47f 3px solid; FONT-STYLE: normal"&gt;&lt;PRE&gt;&lt;FONT face="Courier New" size=2&gt;
&lt;FONT color=#808080&gt;Instruction                 Code Bytes   Comment&lt;/FONT&gt;
&lt;FONT color=#808080&gt;------------------------------------------------------------------------------&lt;/FONT&gt;
mov eax,dword ptr [esp+8] &lt;FONT color=#008000&gt;' 8B 44 24 08  Load the x into eax&lt;/FONT&gt;
mov ecx,dword ptr [esp+4] &lt;FONT color=#008000&gt;' 8B 4C 24 04  Load the y into ecx&lt;/FONT&gt;
add eax,ecx               &lt;FONT color=#008000&gt;' 03 C1        Add eax and ecx, result goes into eax&lt;/FONT&gt;
ret 8                     &lt;FONT color=#008000&gt;' C2 08 00     Pop x and y off the stack, return eax&lt;/FONT&gt;
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;

&lt;P&gt;&lt;FONT face=Verdana size=2&gt;The instructions listed are disassembly copied from the VC++ debugger. The code bytes are what actually executes. The idea is to take those code bytes, write them into a native buffer, acquire a delegate for that buffer, and finally execute the delegate. Here is sample code to run these code bytes from C#:&lt;/FONT&gt;&lt;/P&gt;
&lt;BLOCKQUOTE style="PADDING-RIGHT: 5px; PADDING-LEFT: 5px; BACKGROUND: #fff; BORDER-LEFT: #47f 3px solid; FONT-STYLE: normal"&gt;&lt;PRE&gt;&lt;FONT face="Courier New" size=2&gt;
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System; 
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System.Runtime.InteropServices;




&lt;FONT color=#0000ff&gt;class&lt;/FONT&gt; &lt;FONT color=#008080&gt;Program&lt;/FONT&gt;
{
    &lt;FONT color=#0000ff&gt;private delegate&lt;/FONT&gt; &lt;FONT color=#008080&gt;Int32 MyAdd&lt;/FONT&gt;(&lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; x, &lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; y);

    &lt;FONT color=#0000ff&gt;private static void&lt;/FONT&gt; Main() 
    {
        &lt;FONT color=#008000&gt;// A simple Add function&lt;/FONT&gt;
        &lt;FONT color=#008080&gt;Byte&lt;/FONT&gt;[] myAddNativeCodeBytes = &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Byte&lt;/FONT&gt;[]
        {
            0x8B, 0x44, 0x24, 0x08, &lt;FONT color=#008000&gt;// mov eax,dword ptr [esp+8]&lt;/FONT&gt;
            0x8B, 0x4C, 0x24, 0x04, &lt;FONT color=#008000&gt;// mov ecx,dword ptr [esp+4]&lt;/FONT&gt;
            0x03, 0xC1,             &lt;FONT color=#008000&gt;// add eax,ecx&lt;/FONT&gt;
            0xC2, 0x08, 0x00        &lt;FONT color=#008000&gt;// ret 8&lt;/FONT&gt;
        };

        &lt;FONT color=#008000&gt;// We need to push the code bytes into a native buffer&lt;/FONT&gt;
        &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt; myAddNativeCodeBytesPtr = &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt;.Zero;

        &lt;FONT color=#0000ff&gt;try&lt;/FONT&gt;
        {
            &lt;FONT color=#008000&gt;// Allocate the native buffer&lt;/FONT&gt;
            myAddNativeCodeBytesPtr =
                &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.AllocCoTaskMem(myAddNativeCodeBytes.Length);

            &lt;FONT color=#008000&gt;// Push the code bytes over&lt;/FONT&gt;
            &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.Copy(myAddNativeCodeBytes, 0,
                myAddNativeCodeBytesPtr, myAddNativeCodeBytes.Length);

            &lt;FONT color=#008000&gt;// Get a function pointer for the native code bytes&lt;/FONT&gt;
            &lt;FONT color=#008080&gt;MyAdd&lt;/FONT&gt; myAdd = (&lt;FONT color=#008080&gt;MyAdd&lt;/FONT&gt;)&lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.GetDelegateForFunctionPointer(
                myAddNativeCodeBytesPtr, &lt;FONT color=#0000ff&gt;typeof&lt;/FONT&gt;(&lt;FONT color=#008080&gt;MyAdd&lt;/FONT&gt;));

            &lt;FONT color=#008000&gt;// Call the native code bytes&lt;/FONT&gt;
            &lt;FONT color=#008080&gt;Int32&lt;/FONT&gt; result = myAdd(4, 5);

            &lt;FONT color=#008000&gt;// Did it work?&lt;/FONT&gt;
            &lt;FONT color=#008080&gt;Console&lt;/FONT&gt;.WriteLine(&lt;FONT color=#800000&gt;"Result: {0}"&lt;/FONT&gt;, result);
        }

        &lt;FONT color=#0000ff&gt;finally&lt;/FONT&gt;
        {
            &lt;FONT color=#008000&gt;// Free the native buffer&lt;/FONT&gt;
            &lt;FONT color=#0000ff&gt;if&lt;/FONT&gt; (myAddNativeCodeBytesPtr != &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt;.Zero)
            {
                &lt;FONT color=#008080&gt;Marshal&lt;/FONT&gt;.FreeCoTaskMem(myAddNativeCodeBytesPtr);
                myAddNativeCodeBytesPtr = &lt;FONT color=#008080&gt;IntPtr&lt;/FONT&gt;.Zero;
            }
        }
    }
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;

&lt;P&gt;&lt;FONT face=Verdana size=2&gt;In this sample I just used &lt;A href="http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemruntimeinteropservicesmarshalclassalloccotaskmemtopic.asp"&gt;Marshal.AllocCoTaskMem()&lt;/A&gt;, but one should actually P/Invoke &lt;A href="http://msdn.microsoft.com/library/en-us/memory/base/virtualallocex.asp"&gt;VirtualAllocEx&lt;/A&gt; and &lt;A href="http://msdn.microsoft.com/library/en-us/memory/base/virtualallocex.asp"&gt;VirtualProtectEx&lt;/A&gt; to ensure the page where the code exists has &lt;B&gt;PAGE_EXECUTE&lt;/B&gt; access. Additionally the above sample is targetted to my personal x86 machine, and will not run on x64 or any other platform for that matter.&lt;/FONT&gt;&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=438323" width="1" height="1"&gt;</content><author><name>devinj</name><uri>http://blogs.msdn.com/members/devinj.aspx</uri></author></entry><entry><title>Accessing Dynamic Generic Methods via Interfaces</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/devinj/archive/2005/07/11/437863.aspx" /><id>http://blogs.msdn.com/devinj/archive/2005/07/11/437863.aspx</id><published>2005-07-12T06:34:00Z</published><updated>2005-07-12T06:34:00Z</updated><content type="html">&lt;P&gt;&lt;FONT face=Verdana size=2&gt;It is possible to use the &lt;A href="http://msdn2.microsoft.com/library/xd5fw18y(en-us,vs.80).aspx"&gt;Reflection.Emit&lt;/A&gt; classes to emit generic methods on a dynamic type. Additionally, dynamic types can implement interfaces making it easy to access it's generic methods (or any of it's published members). Without interfaces, to call a generic method on a dynamic type, a call to &lt;A href="http://msdn2.microsoft.com/library/ms145392(en-us,vs.80).aspx"&gt;MethodInfo.MakeGenericMethod()&lt;/A&gt; is required to bind the generic parameters to real type parameters. Only then can you call &lt;A href="http://msdn2.microsoft.com/library/1ttck9d7(en-us,vs.80).aspx"&gt;MethodInfo.Invoke()&lt;/A&gt; leading to code which can be difficult to read.&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;&lt;FONT face=Verdana size=2&gt;With interfaces you can simply make your method calls as you would with any interface. For example:&lt;/FONT&gt;&lt;/P&gt;



&lt;BLOCKQUOTE STYLE="background:#FFF;border-left:3px solid #47f;padding-left: 5px;padding-right: 5px;font-style:normal"&gt;&lt;PRE&gt;
&lt;FONT face="Courier New" size=2&gt;
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System; 
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System.Reflection; 
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System.Reflection.Emit; 
&lt;FONT color=#0000ff&gt;using&lt;/FONT&gt; System.Threading; 
 
 
 
&lt;FONT color=#0000ff&gt;public interface&lt;/FONT&gt; &lt;FONT color=#008080&gt;MyInterface&lt;/FONT&gt; 
{ 
    &lt;FONT color=#008080&gt;Boolean&lt;/FONT&gt; MyEquals&amp;lt;T&amp;gt;(T x, T y); 
} 
 
 
 
&lt;FONT color=#0000ff&gt;class&lt;/FONT&gt; &lt;FONT color=#008080&gt;Program&lt;/FONT&gt; 
{ 
    &lt;FONT color=#0000ff&gt;private static void&lt;/FONT&gt; Main() 
    { 
        &lt;FONT color=#008000&gt;// Create a dynamic assembly&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ---------------------------------------------------------------------&lt;/FONT&gt; 
        &lt;FONT color=#008080&gt;AssemblyName&lt;/FONT&gt; assemblyName = &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;AssemblyName&lt;/FONT&gt;(&lt;FONT color=#800000&gt;&amp;quot;DynamicAssembly&amp;quot;&lt;/FONT&gt;); 
 
        &lt;FONT color=#008080&gt;AssemblyBuilder&lt;/FONT&gt; assemblyBuilder = 
            &lt;FONT color=#008080&gt;AppDomain&lt;/FONT&gt;.CurrentDomain.DefineDynamicAssembly( 
            assemblyName, &lt;FONT color=#008080&gt;AssemblyBuilderAccess&lt;/FONT&gt;.RunAndSave); 
 
        &lt;FONT color=#008080&gt;ModuleBuilder&lt;/FONT&gt; moduleBuilder = 
            assemblyBuilder.DefineDynamicModule(&lt;FONT color=#800000&gt;&amp;quot;DynamicAssembly.exe&amp;quot;&lt;/FONT&gt;); 
 
        &lt;FONT color=#008000&gt;// Create a type which inherits from MyInterface&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ---------------------------------------------------------------------&lt;/FONT&gt; 
        &lt;FONT color=#008080&gt;TypeBuilder&lt;/FONT&gt; typeBuilder = moduleBuilder.DefineType(&lt;FONT color=#800000&gt;&amp;quot;MyType&amp;quot;&lt;/FONT&gt;, 
            &lt;FONT color=#008080&gt;TypeAttributes&lt;/FONT&gt;.Public | &lt;FONT color=#008080&gt;TypeAttributes&lt;/FONT&gt;.Class); 
 
        typeBuilder.AddInterfaceImplementation(&lt;FONT color=#0000ff&gt;typeof&lt;/FONT&gt;(&lt;FONT color=#008080&gt;MyInterface&lt;/FONT&gt;)); 
 
        &lt;FONT color=#008000&gt;// Define the instance method: bool MyEquals&amp;lt;T&amp;gt;(T x, T, y)&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ---------------------------------------------------------------------&lt;/FONT&gt; 
        &lt;FONT color=#008080&gt;MethodBuilder&lt;/FONT&gt; methodBuilder = typeBuilder.DefineMethod( 
            &lt;FONT color=#800000&gt;&amp;quot;MyEquals&amp;quot;&lt;/FONT&gt;, &lt;FONT color=#008080&gt;MethodAttributes&lt;/FONT&gt;.Public | &lt;FONT color=#008080&gt;MethodAttributes&lt;/FONT&gt;.Virtual, 
            &lt;FONT color=#008080&gt;CallingConventions&lt;/FONT&gt;.Standard); 
 
        &lt;FONT color=#008080&gt;GenericTypeParameterBuilder&lt;/FONT&gt; genericTypeParameterBuilder = 
            methodBuilder.DefineGenericParameters(&lt;FONT color=#800000&gt;&amp;quot;T&amp;quot;&lt;/FONT&gt;)[0]; 
 
        methodBuilder.SetReturnType(&lt;FONT color=#0000ff&gt;typeof&lt;/FONT&gt;(&lt;FONT color=#008080&gt;Boolean&lt;/FONT&gt;)); 
 
        methodBuilder.SetParameters(&lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Type&lt;/FONT&gt;[2] { 
            genericTypeParameterBuilder, genericTypeParameterBuilder } ); 
 
        &lt;FONT color=#008000&gt;// Generate a simple Object.Equals() wrapper&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ----------------------------------------------------------------------&lt;/FONT&gt; 
        &lt;FONT color=#008080&gt;MethodInfo&lt;/FONT&gt; equalsMethodInfo = &lt;FONT color=#0000ff&gt;typeof&lt;/FONT&gt;(&lt;FONT color=#008080&gt;Object&lt;/FONT&gt;).GetMethod( 
            &lt;FONT color=#800000&gt;&amp;quot;Equals&amp;quot;&lt;/FONT&gt;, &lt;FONT color=#008080&gt;BindingFlags&lt;/FONT&gt;.Public | &lt;FONT color=#008080&gt;BindingFlags&lt;/FONT&gt;.Static); 
 
        ILGenerator ilGenerator = methodBuilder.GetILGenerator(); 
 
        ilGenerator.Emit(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Ldarg_1); 
        ilGenerator.Emit(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Box, genericTypeParameterBuilder); 
        ilGenerator.Emit(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Ldarg_2); 
        ilGenerator.Emit(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Box, genericTypeParameterBuilder); 
        ilGenerator.Emit(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Tailcall); 
        ilGenerator.EmitCall(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Call, equalsMethodInfo, &lt;FONT color=#0000ff&gt;null&lt;/FONT&gt;); 
        ilGenerator.Emit(&lt;FONT color=#008080&gt;OpCodes&lt;/FONT&gt;.Ret); 
 
        &lt;FONT color=#008000&gt;// Create the type&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ---------------------------------------------------------------------&lt;/FONT&gt; 
        &lt;FONT color=#008080&gt;Type&lt;/FONT&gt; myType = typeBuilder.CreateType(); 
 
        &lt;FONT color=#008080&gt;MyInterface&lt;/FONT&gt; myInterface = (&lt;FONT color=#008080&gt;MyInterface&lt;/FONT&gt;)&lt;FONT color=#008080&gt;Activator&lt;/FONT&gt;.CreateInstance(myType); 
 
        &lt;FONT color=#008000&gt;// Verify the generated IL works (ugly code)&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ---------------------------------------------------------------------&lt;/FONT&gt; 
        &lt;FONT color=#008080&gt;MethodInfo&lt;/FONT&gt; methodInfo1 = myType.GetMethod(&lt;FONT color=#800000&gt;&amp;quot;MyEquals&amp;quot;&lt;/FONT&gt;); 
 
        &lt;FONT color=#008080&gt;MethodInfo&lt;/FONT&gt; methodInfo2 = methodInfo1.MakeGenericMethod( 
            &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Type&lt;/FONT&gt;[1] { &lt;FONT color=#0000ff&gt;typeof&lt;/FONT&gt;(&lt;FONT color=#008080&gt;Int32&lt;/FONT&gt;) } ); 
 
        Boolean result = (&lt;FONT color=#008080&gt;Boolean&lt;/FONT&gt;)methodInfo2.Invoke( 
            myInterface, &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Object&lt;/FONT&gt;[2] { 5, 4 }); 
 
        result = (&lt;FONT color=#008080&gt;Boolean&lt;/FONT&gt;)methodInfo2.Invoke( 
            myInterface, &lt;FONT color=#0000ff&gt;new&lt;/FONT&gt; &lt;FONT color=#008080&gt;Object&lt;/FONT&gt;[2] { 5, 5 }); 
 
        &lt;FONT color=#008000&gt;// Verify the interface implementation (clean code)&lt;/FONT&gt; 
        &lt;FONT color=#008000&gt;// ---------------------------------------------------------------------&lt;/FONT&gt; 
        result = myInterface.MyEquals&amp;lt;&lt;FONT color=#0000ff&gt;int&lt;/FONT&gt;&amp;gt;(5, 4); 
        result = myInterface.MyEquals&amp;lt;&lt;FONT color=#0000ff&gt;int&lt;/FONT&gt;&amp;gt;(5, 5); 
 
        &lt;FONT color=#0000ff&gt;return&lt;/FONT&gt;; 
    } 
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;



&lt;P&gt;&lt;FONT face=Verdana size=2&gt;After saving the dynamic assembly, &lt;A href="http://www.aisto.com/roeder/dotnet/"&gt;.NET Reflector&lt;/A&gt; shows us the code we generated:&lt;/FONT&gt;&lt;/P&gt;



&lt;BLOCKQUOTE STYLE="background:#FFF;border-left:3px solid #47f;padding-left: 5px;padding-right: 5px;font-style:normal"&gt;&lt;PRE&gt;
&lt;FONT face="Tahoma" size=2&gt;
&lt;FONT color=#1000a0&gt;.method public virtual instance&lt;/FONT&gt; &lt;FONT color=#006018&gt;bool&lt;/FONT&gt; &lt;B&gt;MyEquals&lt;/B&gt;&amp;lt;T&amp;gt;(!!0, !!0) &lt;FONT color=#1000a0&gt;cil managed&lt;/FONT&gt; 
{ 
    &lt;FONT color=#808080&gt;// Code Size: 20 byte(s)&lt;/FONT&gt; 
    &lt;FONT color=#1000a0&gt;.maxstack&lt;/FONT&gt; 2 
    L_0000: ldarg.1 
    L_0001: box !!0 
    L_0006: ldarg.2 
    L_0007: box !!0 
    L_000c: tail 
    L_000e: call &lt;FONT color=#006018&gt;bool object&lt;/FONT&gt;::&lt;FONT color=#006018&gt;Equals&lt;/FONT&gt;(&lt;FONT color=#006018&gt;object&lt;/FONT&gt;, &lt;FONT color=#006018&gt;object&lt;/FONT&gt;) 
    L_0013: ret 
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;



&lt;P&gt;&lt;FONT face=Verdana size=2&gt;Or the C# view:&lt;/FONT&gt;&lt;/P&gt;



&lt;BLOCKQUOTE STYLE="background:#FFF;border-left:3px solid #47f;padding-left: 5px;padding-right: 5px;font-style:normal"&gt;&lt;PRE&gt;
&lt;FONT face="Tahoma" size=2&gt;
&lt;FONT color=#1000a0&gt;public override&lt;/FONT&gt; &lt;FONT color=#006018&gt;bool&lt;/FONT&gt; &lt;B&gt;MyEquals&lt;/B&gt;&amp;lt;&lt;B&gt;T&lt;/B&gt;&amp;gt;(T local1, T local2) 
{ 
    &lt;FONT color=#1000a0&gt;return&lt;/FONT&gt; &lt;FONT color=#006018&gt;object&lt;/FONT&gt;.&lt;FONT color=#006018&gt;Equals&lt;/FONT&gt;(local1, local2); 
}
&lt;/FONT&gt;
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=437863" width="1" height="1"&gt;</content><author><name>devinj</name><uri>http://blogs.msdn.com/members/devinj.aspx</uri></author></entry></feed>