<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" version="2.0">
  <channel>
    <title>Marcus' Blog</title>
    <link>http://www.heege.net/blog/</link>
    <description>Notes in and about C++/CLI - the "chosen" language</description>
    <copyright>Marcus Heege</copyright>
    <lastBuildDate>Fri, 06 Apr 2007 09:13:08 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 1.7.5016.2</generator>
    <managingEditor>marcus@heege.net</managingEditor>
    <webMaster>marcus@heege.net</webMaster>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,94167d73-7954-4a5c-a745-dc60d352cdef.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,94167d73-7954-4a5c-a745-dc60d352cdef.aspx</pingback:target>
      <title>Marshalling native function pointers</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,94167d73-7954-4a5c-a745-dc60d352cdef.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,94167d73-7954-4a5c-a745-dc60d352cdef.aspx</link>
      <pubDate>Fri, 06 Apr 2007 09:13:08 GMT</pubDate>
      <description>&lt;p&gt;
   Now that the book is written and all urgent tasks I had to defer due to the book are
   done, I find some time to blog about technical topics.
&lt;/p&gt;
&lt;p&gt;
   Recently, a customer asked me how to marshal function pointers across managed / unmanaged
   interop boundaries. If you know a simple API and two attributes and if you are aware
   of a pitfall specific to marshaling function pointers, the job can be quite easy.
&lt;/p&gt;
&lt;p&gt;
   To discuss this topic, consider the following simple API:
&lt;/p&gt;
&lt;code&gt; namespace NativeAPI&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;struct CallbackData&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;int i;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;double d;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;};&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;typedef void (*PFNCallback)(CallbackData* p);&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;class SampleClass&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;PFNCallback _pfn;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;public:&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;SampleClass(PFNCallback pfn);&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;void F();&lt;br /&gt;
&amp;nbsp;&amp;nbsp;};&lt;br /&gt;
}&lt;br /&gt;
&lt;/code&gt; 
&lt;p&gt;
   In my book I focus on wrapping class libraries that use virtual functions for callbacks
   instead of function pointers, because virtual functions are the typical C++-like approach
   for callbacks. But obviously, a lot of C++ class libraries have their roots in C which
   can force you to care about arguments of function pointer types.
&lt;/p&gt;
&lt;p&gt;
   The managed equivalent to a native function pointer is a delegate. There are different
   ways to map between delegates and function pointers. The following code shows a delegate
   that can be mapped to the native function pointer of type &lt;code&gt;PFNCallback&lt;/code&gt;:
&lt;/p&gt;
&lt;code&gt; namespace ManagedWrapper { &amp;nbsp;&amp;nbsp;using namespace System::Runtime::InteropServices;&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;[StructLayout(LayoutKind::Sequential)]&lt;br /&gt;
&amp;nbsp;&amp;nbsp;public value struct CallbackData&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;int i;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;double d;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;};&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;[UnmanagedFunctionPointer(CallingConvention::Cdecl)]&lt;br /&gt;
&amp;nbsp;&amp;nbsp;public delegate void CallbackDelegate(CallbackData% p);&lt;br /&gt;
} &lt;/code&gt; 
&lt;p&gt;
   Notice that I first define a managed wrapper type for CallbackData that has the same
   binary layout as its native counterpart. This is done with the StructLayout attribute.
   The attribute is only used for documentation purposes, because sequential layout is
   the default setting for custom value types defined in C++/CLI (and C#). The delegate
   type has the UnmanagedFunctionPointerAttribute, which is not optional in this case.
   Using this attribute, you can specify the calling convention of the native function
   pointer type. In the native API's header file, the &lt;code&gt;PFNCallback&lt;/code&gt; is defined
   without an explicit calling convention specification – this is not recommended, but
   it occurs quite often. In this case, the function pointer type has the default calling
   convention, which depends on compiler switches. If no compiler switch is used, the
   default calling convention for C-style function pointers is &lt;code&gt;__cdecl&lt;/code&gt;.
   Using the compiler switches /Gz or /Gr, the default calling convention can be changed
   to &lt;code&gt;__stdcall&lt;/code&gt; or &lt;code&gt;__fastcall&lt;/code&gt;. In the concrete scenario that
   my customer faced, neither /Gz nor /Gr are used. To express that the &lt;code&gt;CallbackDelegate&lt;/code&gt; should
   be marshaled to a &lt;code&gt;__cdecl&lt;/code&gt; function pointer, the UnmanagedFunctionPointerAttribute
   is necessary. If the native function pointer is a &lt;code&gt;__fastcall&lt;/code&gt; function,
   you can not provide a simple mapping, because calling &lt;code&gt;__fastcall&lt;/code&gt; functions
   from managed code is not supported by the current version (2.0) of the CLR. Once you
   have properly defined the delegate, you can use the function &lt;code&gt;Marshal::GetFunctionPointerForDelegate&lt;/code&gt; to
   receive a pointer to a native-&gt;managed thunk for the delegate. This pointer can then
   be passed to native code. If native code uses this pointer for function calls, the
   thunk performs the native-&amp;gt;managed transition and invokes the delegate. To wrap &lt;code&gt;NativeAPI::SampleClass&lt;/code&gt;,
   you can implement the following wrapper class: 
&lt;/p&gt;
&lt;code&gt; namespace ManagedWrapper&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;public ref class SampleClass&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;NativeAPI::SampleClass* _pWrappedObject;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;CallbackDelegate^ _callbackDelegate;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;public:&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;SampleClass(CallbackDelegate^ cbd);&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;void F();&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;~SampleClass();&lt;br /&gt;
&amp;nbsp;&amp;nbsp;};&lt;br /&gt;
}&lt;br /&gt;
&lt;/code&gt; 
&lt;p&gt;
   In the constructor of this wrapper class, you can use &lt;code&gt;Marshal::GetFunctionPointerForDelegate&lt;/code&gt; to
   determine the function pointer that is passed to the constructor of &lt;code&gt;NativeLib::SampleClass&lt;/code&gt;.
   The following code shows the implementation of &lt;code&gt;ManagedWrapper::SampleClass&lt;/code&gt;. 
&lt;/p&gt;
&lt;code&gt; namespace ManagedWrapper&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;SampleClass::SampleClass(CallbackDelegate^ callbackDelegate)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;: _callbackDelegate(callbackDelegate),&lt;br /&gt;
&amp;nbsp;&amp;nbsp;_pWrappedObject(nullptr)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;IntPtr p = Marshal::GetFunctionPointerForDelegate(_callbackDelegate);&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;_pWrappedObject = new NativeAPI::SampleClass((NativeAPI::PFNCallback)p.ToPointer());&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if (!_pWrappedObject)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;throw gcnew OutOfMemoryException("Could not allocate
memory on C++ free store");&lt;br /&gt;
&amp;nbsp;&amp;nbsp;}&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;void SampleClass::F()&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;_pWrappedObject-&gt;F();&lt;br /&gt;
&amp;nbsp;&amp;nbsp;}&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;SampleClass::~SampleClass()&lt;br /&gt;
&amp;nbsp;&amp;nbsp;{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;NativeAPI::SampleClass* pWrappedObject = _pWrappedObject;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;_pWrappedObject = nullptr;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;delete _pWrappedObject;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;}&lt;br /&gt;
}&lt;br /&gt;
&lt;/code&gt; 
&lt;p&gt;
   Notice that in the member initialization list of the constructor, I first store a
   handle to the target delegate in a member variable. This is important, to control
   the lifetime of the thunk. At the first view, one might think that the thunk manages
   a tracking handle to the target delegate, which would keep the delegate alive as long
   as the thunk exists. However, the opposite is the case. It is not the thunk that keeps
   the delegate alive; the delegate keeps the thunk alive: The thunk is guaranteed to
   exist only as long as the delegate exists. The thunk only contains a weak reference
   to the target delegate which it can use for invocation if the delegate is not garbage
   collected. Due to this implementation, the following code would definitely be a bug: 
&lt;/p&gt;
&lt;code&gt; SampleClass::SampleClass(CallbackDelegate^ callbackDelegate)&lt;br /&gt;
: _pWrappedObject(nullptr)&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;IntPtr p = Marshal::GetFunctionPointerForDelegate(callbackDelegate);&lt;br /&gt;
&amp;nbsp;&amp;nbsp;_pWrappedObject = new NativeAPI::SampleClass((NativeAPI::PFNCallback)p.ToPointer());&lt;br /&gt;
&amp;nbsp;&amp;nbsp;if (!_pWrappedObject)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;throw gcnew OutOfMemoryException("Could not allocate memory
on C++ free store");&lt;br /&gt;
}&lt;br /&gt;
&lt;/code&gt; 
&lt;p&gt;
   Since the delegate that was used to create the thunk (and the function pointer referring
   to the thunk) is not stored in a member variable, it can be GCed unless other references
   to the delegate exist. When this delegate is GCed, the thunk can be removed as well.
   Notice that the thunk is not automatically removed when its target delegate is deleted,
   because the thunk and the delegate are created on different heaps: the delegate is
   instantiated on the GC heap, whereas the thunk is created on a heap that I like to
   call the CLR's code heap. An important difference of these heaps is that the code
   heap consists of memory pages that have the attribute PAGE_EXECUTE_READWRITE. The
   following code shows you some internals about Marshal::GetDelegateForFunctionPointer 
&lt;/p&gt;
&lt;code&gt; // GFPFDTests.cpp&lt;br /&gt;
// build with "CL /clr GFPFDTests.cpp"&lt;br /&gt;
&lt;br /&gt;
#include "windows.h"&lt;br /&gt;
&lt;br /&gt;
using namespace System;&lt;br /&gt;
using namespace System::Diagnostics;&lt;br /&gt;
using namespace System::Runtime::InteropServices;&lt;br /&gt;
&lt;br /&gt;
typedef void (__cdecl* PFN)();&lt;br /&gt;
&lt;br /&gt;
[UnmanagedFunctionPointer(CallingConvention::Cdecl)]&lt;br /&gt;
public delegate void PFNDelegate();&lt;br /&gt;
&lt;br /&gt;
// managed function has __cdecl calling convention&lt;br /&gt;
// therefore, a PFN can point to it.&lt;br /&gt;
void __cdecl F()&lt;br /&gt;
{&lt;br /&gt;
Console::WriteLine("::F called");&lt;br /&gt;
}&lt;br /&gt;
int main(array&lt;System::String ^&gt; ^args)&lt;br /&gt;
   {&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;PFNDelegate^ d1 = gcnew PFNDelegate(F);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;IntPtr p1 = Marshal::GetFunctionPointerForDelegate(d1);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;IntPtr p2 = Marshal::GetFunctionPointerForDelegate(d1);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;// calling M::GFPFD twice for same delegate returns same thunk&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;Debug::Assert(p1 == p2);&lt;br /&gt;
   &lt;br /&gt;
   &amp;nbsp;&amp;nbsp;PFNDelegate^ d2 = gcnew PFNDelegate(F);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;p2 = Marshal::GetFunctionPointerForDelegate(d2);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;// calling M::GFPFS twice for different delegates returns&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;// different thunks even if delegate target is the same&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;Debug::Assert(p1 != p2);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;MEMORY_BASIC_INFORMATION mbi;&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;VirtualQuery(p1.ToPointer(), &amp;mbi, sizeof(mbi));&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;// thunks are allocated on a heap that consits of pages &amp;nbsp;&amp;nbsp;//
   with the PAGE_EXECUTE_READWRITE flag&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;Debug::Assert((mbi.Protect &amp; PAGE_EXECUTE_READWRITE) ==&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;PAGE_EXECUTE_READWRITE);&lt;br /&gt;
   &lt;br /&gt;
   &amp;nbsp;&amp;nbsp;void* pD1 = *(void**)&amp;d1; // hack to get native pointer to delegate&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;VirtualQuery(pD1, &amp;mbi, sizeof(mbi));&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;// .NET objects are allocated on the GC heap which consists of&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;// pages with the PAGE_READWRITE flag&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;Debug::Assert((mbi.Protect &amp; PAGE_READWRITE) ==&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;PAGE_READWRITE);&lt;br /&gt;
   &lt;br /&gt;
   &amp;nbsp;&amp;nbsp;PFN pfn = (PFN)p1.ToPointer();&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;pfn();&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;WeakReference wr(d1);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;d1 = nullptr;&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;GC::Collect(2);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;Debug::Assert(!wr.IsAlive);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;try&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;{&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;pfn();&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// since the target delegate does not exist any more,&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// an exception is thrown here and the line below is&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// not executed&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// if you execute this in a debugger, you will likely see&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// a "Managed Debugging Assistant" instead.&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// MDAs are CLR internal assertion-like constructs &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Debug::Assert(FALSE);&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;}&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;catch (System::AccessViolationException^ ex)&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;{&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Debug::WriteLine("Expected exception");&lt;br /&gt;
   &amp;nbsp;&amp;nbsp;}&lt;br /&gt;
   }&lt;br /&gt;

&lt;/code&gt; 
&lt;p&gt;
   In this post I have discussed how to treat marshal delegates to native function pointers.
   However, I have not discussed what you should do if the signature of the native function
   requires parameter marshalling. This will be addressed in my next post. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=94167d73-7954-4a5c-a745-dc60d352cdef"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,0440bf0e-243d-4900-a81f-16aee3f4b89c.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,0440bf0e-243d-4900-a81f-16aee3f4b89c.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">A long project is comming to an end soon.
   After one year of writing, my <a href="http://www.amazon.com/Expert-Visual-C++-CLI/dp/1590597567/ref=pd_sim_b_4/104-6627705-3354307">book</a> will
   be finished soon. 3 chapters need some minor changes. All other chapters of my book
   are now going to be copy edited. The book will summarize essentail parts of my research
   on C++/CLI in the last two years. Notice that the announcement in amazon.com is not
   100% correct. The title of the book will be "Expert C++/CLI: .NET for Visual C++ programmers"
   and the release date will be Mid March. <img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=0440bf0e-243d-4900-a81f-16aee3f4b89c" /></body>
      <title>Finishing my book</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,0440bf0e-243d-4900-a81f-16aee3f4b89c.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,0440bf0e-243d-4900-a81f-16aee3f4b89c.aspx</link>
      <pubDate>Sat, 13 Jan 2007 09:00:07 GMT</pubDate>
      <description>A long project is comming to an end soon. After  one year of writing, my &lt;a href="http://www.amazon.com/Expert-Visual-C++-CLI/dp/1590597567/ref=pd_sim_b_4/104-6627705-3354307"&gt;book&lt;/a&gt; will
be finished soon. 3 chapters need some minor changes. All other chapters of my book
are now going to be copy edited. The book will summarize essentail parts of my research
on C++/CLI in the last two years. Notice that the announcement in amazon.com is not
100% correct. The title of the book will be "Expert C++/CLI: .NET for Visual C++ programmers"
and the release date will be Mid March. &lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=0440bf0e-243d-4900-a81f-16aee3f4b89c"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,31643b9e-124b-4a57-82c6-08acb6a09f5f.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,31643b9e-124b-4a57-82c6-08acb6a09f5f.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      1) Since April, 1st I am an MVP for Visual C++.
   </p>
        <p>
      2) My first article in the MSDN Magazine has been published: <a href="http://msdn.microsoft.com/msdnmag/issues/06/05/MixAndMatch/default.aspx">http://msdn.microsoft.com/msdnmag/issues/06/05/MixAndMatch/default.aspx</a></p>
        <img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=31643b9e-124b-4a57-82c6-08acb6a09f5f" />
      </body>
      <title>Some personal things</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,31643b9e-124b-4a57-82c6-08acb6a09f5f.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,31643b9e-124b-4a57-82c6-08acb6a09f5f.aspx</link>
      <pubDate>Tue, 11 Apr 2006 12:15:43 GMT</pubDate>
      <description>&lt;p&gt;
   1) Since April, 1st I am an MVP for Visual C++.
&lt;/p&gt;
&lt;p&gt;
   2) My first article in the MSDN Magazine has been published: &lt;a href="http://msdn.microsoft.com/msdnmag/issues/06/05/MixAndMatch/default.aspx"&gt;http://msdn.microsoft.com/msdnmag/issues/06/05/MixAndMatch/default.aspx&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=31643b9e-124b-4a57-82c6-08acb6a09f5f"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,13f270f4-a0fb-4439-8467-0e56ec4d7aef.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,13f270f4-a0fb-4439-8467-0e56ec4d7aef.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      In <a href="news://msnews.microsoft.com/microsoft.public.dotnet.languages.vc">news://msnews.microsoft.com/microsoft.public.dotnet.languages.vc</a> Edward
      Diener asked an <a href="news://msnews.microsoft.com/microsoft.public.dotnet.languages.vc">very
      interesting question</a>: Why can't I call a function having arguments of a native
      type like std::string from another assembly? 
   </p>
        <div>Assume you have some code like this one:
   </div>
        <div> 
   </div>
        <div>
          <div>
            <font face="Courier New">// Conversions.cpp</font>
          </div>
          <div>
            <font face="Courier New">// compile with "CL /clr /LD conversions.cpp"</font>
          </div>
          <div>
            <font face="Courier New">// output: mixed code assembly Conversions.dll</font>
          </div>
          <div>
            <font face="Courier New">#include &lt;string&gt;</font>
          </div>
          <div>
            <font face="Courier New">
            </font> 
      </div>
          <div>
            <font face="Courier New">public ref class Conversions<br />
         {<br />
         public:<br />
           static void S2S(System::String^ s1, std::string&amp; s2) { /* ... */ }<br />
         };</font>
          </div>
          <div> 
      </div>
        </div>
        <div>This code should compile as expected, however, it would not give you the expected
      result!
   </div>
        <div> 
   </div>
        <div>The code below looks like a suitable client:
   </div>
        <div> 
   </div>
        <div>
          <font face="Courier New">// ConversionsClient.cpp</font>
        </div>
        <div>
          <font face="Courier New">// compile with "CL /clr ConversionsClient.cpp"</font>
        </div>
        <div>
          <font face="Courier New">#using "Conversions.dll" </font>
        </div>
        <div>
          <font face="Courier New">#include &lt;string&gt;</font>
        </div>
        <div>
          <font face="Courier New">int main()<br />
      {<br />
        std::string s;<br />
        Conversions::S2S("asdf", s);<br />
      }</font>
        </div>
        <div>
          <div> 
      </div>
          <div>If you try to compile this code, you will get a disappointing error message: 
      </div>
          <div> 
      </div>
          <div>error C3767: 'Conversions::S2S': candidate function(s) not accessible
      </div>
          <div> 
      </div>
          <div>Why is a public static function S2S of a public type Convesions not accessible?
      </div>
          <div> 
      </div>
        </div>
        <div>To use the native type std::string in managed code, the compiler generates a managed
      value type std::string in the assembly where std::string is used. This managed wrapper
      value type is private, therefore, the Conversions::S2S cannot be called from
      outside the assembly even though it is a public function of a public type.
   </div>
        <div> 
   </div>
        <div>At the first view it seems, key to the solution is to make sure the compiler
      generates a public type for std::string, in theory this is possible, however it would
      not help to solve the problem. In fact the native wrapper type has been defined as
      a private type for some good reasons.
   </div>
        <div> 
   </div>
        <div>Assume the native wrapper type for std::string was public. To call S2S, one would
      have to pass a tracking handle to a System::String, defined in mscolib.dll, and a
      value of the type std::string defined in the assembly Conversions.dll. The std::string
      type that we pass in ConversionsClient.cpp is a different one! It is the native wrapper
      type defined in ConversionsClient.cpp - not the native wapper type defined in Conversions.dll.
      Therefore, the parameters would not match.
   </div>
        <div> 
   </div>
        <div>So how can we solve this problem?
   </div>
        <div> 
   </div>
        <div>The origin of the problem is the fact, that type identity rules of .NET do not
      allways mix well with the type identity rules of native C++. To solve this problem,
      you can switch back to the world of native code sharing without loosing you managed
      code features. Simply create a mixed code static library:
   </div>
        <div> 
   </div>
        <div>Create a static mixed code library from the code :
   </div>
        <div> 
   </div>
        <div>
          <div>
            <font face="Courier New">// ConversionsLib.cpp</font>
          </div>
          <div>
            <font face="Courier New">// compile with "CL /c /clr ConversionsLib.cpp"</font>
          </div>
          <div>
            <font face="Courier New">// make lib with "LIB ConversionsLib.obj"</font>
          </div>
          <div>
            <font face="Courier New">// output: mixed code static library ConversionsLib.lib</font>
          </div>
          <div>
            <font face="Courier New">
            </font> 
      </div>
          <div>
            <font face="Courier New">#include &lt;string&gt;</font>
          </div>
          <div>
            <font face="Courier New">void S2S(System::String^ s1, std::string&amp; s2) {
         /* ... */ }<br /></font>
          </div>
        </div>
        <div>Create a client from the code below.
   </div>
        <div> 
   </div>
        <div>
          <font face="Courier New">// ConversionsLibClient.cpp</font>
        </div>
        <div>
          <font face="Courier New">// compile with "CL /clr ConversionsLibClient.cpp"</font>
        </div>
        <div>
          <font face="Courier New">#include &lt;string&gt;</font>
        </div>
        <div>
          <font face="Courier New">
          </font> 
   </div>
        <div>
          <font face="Courier New">#pragma comment (lib, "ConversionsLib.lib")</font>
        </div>
        <div>
          <font face="Courier New">void S2S(System::String^ s1, std::string&amp; s2);</font>
        </div>
        <div>
          <font face="Courier New">
          </font> 
   </div>
        <div>
          <font face="Courier New">int main()<br />
      {<br />
        std::string s;<br />
        S2S("asdff", s);<br />
      }</font>
        </div>
        <div> 
   </div>
        <div>Conclusion: Beware the different type identity rules. Native types are identifies
      by their namespace-qualified typename, managed types are identified by their assembly-
      and namespace-qualifies typename. If you need native type identity rules, use native
      code sharing features, if you need managed type identity, use managed code sharing
      features.
   </div>
        <img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=13f270f4-a0fb-4439-8467-0e56ec4d7aef" />
      </body>
      <title>Mixed mode DLLs: Problem with public functions using native types as arguments</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,13f270f4-a0fb-4439-8467-0e56ec4d7aef.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,13f270f4-a0fb-4439-8467-0e56ec4d7aef.aspx</link>
      <pubDate>Tue, 21 Mar 2006 17:36:54 GMT</pubDate>
      <description>&lt;p&gt;
   In &lt;a href="news://msnews.microsoft.com/microsoft.public.dotnet.languages.vc"&gt;news://msnews.microsoft.com/microsoft.public.dotnet.languages.vc&lt;/a&gt;&amp;nbsp;Edward
   Diener asked an &lt;a href="news://msnews.microsoft.com/microsoft.public.dotnet.languages.vc"&gt;very
   interesting question&lt;/a&gt;: Why can't I call a function having arguments of a native
   type like std::string from another assembly? 
&lt;/p&gt;
&lt;div&gt;Assume you have some code like this one:
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// Conversions.cpp&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// compile with "CL /clr /LD conversions.cpp"&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// output: mixed code assembly Conversions.dll&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;#include &amp;lt;string&amp;gt;&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&amp;nbsp;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;public ref class Conversions&lt;br&gt;
      {&lt;br&gt;
      public:&lt;br&gt;
      &amp;nbsp; static void S2S(System::String^ s1, std::string&amp;amp; s2) { /* ... */ }&lt;br&gt;
      };&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&amp;nbsp;
   &lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;This code should compile as expected, however, it would not give you the expected
   result!
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;The code below looks like a suitable client:
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;// ConversionsClient.cpp&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;// compile with "CL /clr ConversionsClient.cpp"&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;#using "Conversions.dll"&amp;nbsp;&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;#include &amp;lt;string&amp;gt;&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;int main()&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; std::string s;&lt;br&gt;
   &amp;nbsp; Conversions::S2S("asdf", s);&lt;br&gt;
   }&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;
   &lt;div&gt;&amp;nbsp;
   &lt;/div&gt;
   &lt;div&gt;If you try to compile this code, you will get a disappointing error message: 
   &lt;/div&gt;
   &lt;div&gt;&amp;nbsp;
   &lt;/div&gt;
   &lt;div&gt;error C3767: 'Conversions::S2S': candidate function(s) not accessible
   &lt;/div&gt;
   &lt;div&gt;&amp;nbsp;
   &lt;/div&gt;
   &lt;div&gt;Why is a public static function S2S of a public type Convesions not accessible?
   &lt;/div&gt;
   &lt;div&gt;&amp;nbsp;
   &lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;To use the native type std::string in managed code, the compiler generates a&amp;nbsp;managed
   value type std::string in the assembly where std::string is used. This managed wrapper
   value type is private, therefore, the&amp;nbsp;Conversions::S2S cannot be called from
   outside the assembly even though it is a public function of a public type.
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;At the first view it seems, key to the solution is to make sure the compiler
   generates a public type for std::string, in theory this is possible, however it would
   not help to solve the problem. In fact the native wrapper type has been defined as
   a private type for some good reasons.
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;Assume the native wrapper type for std::string was public. To call S2S, one would
   have to pass a tracking handle to a System::String, defined in mscolib.dll, and a
   value of the type std::string defined in the assembly Conversions.dll. The std::string
   type that we pass in ConversionsClient.cpp is a different one! It is the native wrapper
   type defined in ConversionsClient.cpp - not the native wapper type defined in Conversions.dll.
   Therefore, the parameters would not match.
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;So how can we solve this problem?
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;The origin of the problem is the fact, that type identity rules of .NET do not
   allways mix well with the type identity rules of native C++. To solve this problem,
   you can switch back to the world of native code sharing without loosing you managed
   code features. Simply create a mixed code static library:
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;Create a static mixed code library from the code :
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// ConversionsLib.cpp&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// compile with "CL /c /clr ConversionsLib.cpp"&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// make lib with "LIB ConversionsLib.obj"&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;// output: mixed code static library&amp;nbsp;ConversionsLib.lib&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&amp;nbsp;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;#include &amp;lt;string&amp;gt;&lt;/font&gt;
   &lt;/div&gt;
   &lt;div&gt;&lt;font face="Courier New"&gt;void S2S(System::String^ s1, std::string&amp;amp; s2) {
      /* ... */ }&lt;br&gt;
      &lt;/font&gt;
   &lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;Create a client from the code below.
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;// ConversionsLibClient.cpp&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;// compile with "CL /clr ConversionsLibClient.cpp"&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;#include &amp;lt;string&amp;gt;&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;#pragma comment (lib, "ConversionsLib.lib")&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;void S2S(System::String^ s1, std::string&amp;amp; s2);&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;&lt;font face="Courier New"&gt;int main()&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; std::string s;&lt;br&gt;
   &amp;nbsp; S2S("asdff", s);&lt;br&gt;
   }&lt;/font&gt;
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div&gt;Conclusion: Beware the different type identity rules. Native types are identifies
   by their namespace-qualified typename, managed types are identified by their assembly-
   and namespace-qualifies typename. If you need native type identity rules, use native
   code sharing features, if you need managed type identity, use managed code sharing
   features.
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=13f270f4-a0fb-4439-8467-0e56ec4d7aef"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,589239d3-b21b-430e-911b-7b355eef8b63.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,589239d3-b21b-430e-911b-7b355eef8b63.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.mybadhairday.com/cppcliinstall.html">http://www.mybadhairday.com/cppcliinstall.html</a>
        </p>
        <img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=589239d3-b21b-430e-911b-7b355eef8b63" />
      </body>
      <title>Reflector Add-In for C++/CLI available</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,589239d3-b21b-430e-911b-7b355eef8b63.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,589239d3-b21b-430e-911b-7b355eef8b63.aspx</link>
      <pubDate>Fri, 20 Jan 2006 11:07:12 GMT</pubDate>
      <description>&lt;p&gt;
   &lt;a href="http://www.mybadhairday.com/cppcliinstall.html"&gt;http://www.mybadhairday.com/cppcliinstall.html&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=589239d3-b21b-430e-911b-7b355eef8b63"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,d5e2c3da-ff4d-40bc-bea9-9da8ec9e091e.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,d5e2c3da-ff4d-40bc-bea9-9da8ec9e091e.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      When a cpp file is compiled with /clr, a managed object file is created. In most scenarios,
      such a managed object file contains only managed code. However, there are two scenarios
      that end up in a managed object file with managed and native code:
   </p>
        <ol>
          <li>
         When #pragma unmanaged is used 
      </li>
          <li>
         When the C++ file contains a function with C++ constructs that are not mappable to
         IL code.</li>
        </ol>
        <p>
      Managed object files with native code imply a certain danger: They can end up in uninitialized
      state, as shown in the following sample:
   </p>
        <p>
      In the code below, i is a global variable initialized with the return value of getValue().
      There are two exported functions that simply return i. One is the managed function
      fManaged and the other one is the unmanaged function fUnmanaged.<br /></p>
        <p>
          <font face="Courier New">&lt;code language=”C++/CLI” filename=”MixedLib.cpp” compileWith=”CL
      /LD /clr MixedLib.cpp”&gt;<br />
      #pragma unmanaged<br />
      __declspec(noinline) int getValue() {<br />
        return 42;<br />
      }</font>
        </p>
        <p>
          <font face="Courier New">int i = getValue();</font>
        </p>
        <p>
          <font face="Courier New">__declspec(dllexport) int fUnmanaged()<br />
      {<br />
        return i;<br />
      }</font>
        </p>
        <p>
          <font face="Courier New">#pragma managed<br />
      __declspec(dllexport) int fManaged()<br />
      {<br />
        return i;<br />
      }<br />
      &lt;/code&gt;</font>
        </p>
        <p>
      Before fManaged is executed the first time, the module constructor is called. The
      module constructor calls getValue to initialize the global variable i. However, if
      fUnmanaged is called before fManaged is called the first time, the variable i will
      be returned before it is initialized. To reproduce this scenario, you can use the
      client application below.
   </p>
        <p>
          <font face="Courier New">&lt;code language=”C++/CLI” filename=”TestApp.cpp” compileWith=”CL
      /clr TestApp.cpp”&gt;<br />
      #include &lt;stdio.h&gt;</font>
        </p>
        <p>
          <font face="Courier New">#pragma comment(lib, "testlib.lib")</font>
        </p>
        <p>
          <font face="Courier New">__declspec(dllimport) int fUnmanaged();<br />
      __declspec(dllimport) int fManaged();</font>
        </p>
        <p>
          <font face="Courier New">int main()<br />
      {<br />
        printf("fUnmanaged returns %d\n", fUnmanaged());<br />
        printf("fManaged returns %d\n", fManaged());<br />
        printf("fUnmanaged returns %d\n", fUnmanaged());<br />
      }<br />
      &lt;/code&gt;</font>
        </p>
        <p>
      If you start TestApp.exe, you will get the following output:
   </p>
        <p>
      fUnmanaged returns 0<br />
      fManaged returns 42<br />
      fUnmanaged returns 42
   </p>
        <p>
      The easiest way to avoid these problems is to make sure that files compiled with /clr
      contain only managed code and to leave the native code in cpp files compiled without
      /clr. If you consider using #pragma unmanaged or unmappable C++ constructs in files
      compiled with /clr, you should be aware that all global variables and static member
      variables of that file, are initialized by the module initializer. This is even true
      if the variable is of a native type.
   </p>
        <p>
      The compiler's ability to automatically compile a function with unmappable C++ constructs
      to native code can cause a scenario where you get mixed code object files without
      even realizing it. Fortunately a compiler warning C4793 can be emitted in this scenario.
      C4793 is a level 2 warning. To get it, you either have to set the warning level to
      2, or you have to use a compiler switch to make it a level 1 warning, as shown in
      the following code.
   </p>
        <p>
          <font face="Courier New">&lt;code language="C++/CLI" 
      <br />
           filename=" UnmappableConstructs.cpp" 
      <br />
           compileWith="cl /c /clr /w14793 UnmappableConstructs.cpp"&gt;<br />
      void f()<br />
      {<br />
        __asm int 3;<br />
      }<br />
      &lt;/code&gt;</font>
        </p>
        <p>
      When you compile this code, the C++ compiler will emit the warning C4793 with the
      following message:
   </p>
        <p>
      UnmappableConstructs.cpp(3) : warning C4793: '__asm' : causes native code generation
      for function 'void f(void)'<br />
              UnmappableConstructs.cpp(1) : see declaration
      of 'f'<br /></p>
        <img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=d5e2c3da-ff4d-40bc-bea9-9da8ec9e091e" />
      </body>
      <title>Avoid native code in managed object files (".obj" files)</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,d5e2c3da-ff4d-40bc-bea9-9da8ec9e091e.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,d5e2c3da-ff4d-40bc-bea9-9da8ec9e091e.aspx</link>
      <pubDate>Thu, 12 Jan 2006 15:29:45 GMT</pubDate>
      <description>&lt;p&gt;
   When a cpp file is compiled with /clr, a managed object file is created. In most scenarios,
   such a managed object file contains only managed code. However, there are two scenarios
   that end up in a managed object file with managed and native code:
&lt;/p&gt;
&lt;ol&gt;
   &lt;li&gt;
      When #pragma unmanaged is used 
   &lt;li&gt;
      When the C++ file contains a function with C++ constructs that are not mappable to
      IL code.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
   Managed object files with native code imply a certain danger: They can end up in uninitialized
   state, as shown in the following sample:
&lt;/p&gt;
&lt;p&gt;
   In the code below, i is a global variable initialized with the return value of getValue().
   There are two exported functions that simply return i. One is the managed function
   fManaged and the other one is the unmanaged function fUnmanaged.&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;&amp;lt;code language=”C++/CLI” filename=”MixedLib.cpp” compileWith=”CL
   /LD /clr MixedLib.cpp”&amp;gt;&lt;br&gt;
   #pragma unmanaged&lt;br&gt;
   __declspec(noinline) int getValue() {&lt;br&gt;
   &amp;nbsp; return 42;&lt;br&gt;
   }&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;int i = getValue();&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;__declspec(dllexport) int fUnmanaged()&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; return i;&lt;br&gt;
   }&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;#pragma managed&lt;br&gt;
   __declspec(dllexport) int fManaged()&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; return i;&lt;br&gt;
   }&lt;br&gt;
   &amp;lt;/code&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   Before fManaged is executed the first time, the module constructor is called. The
   module constructor calls getValue to initialize the global variable i. However, if
   fUnmanaged is called before fManaged is called the first time, the variable i will
   be returned before it is initialized. To reproduce this scenario, you can use the
   client application below.
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;&amp;lt;code language=”C++/CLI” filename=”TestApp.cpp” compileWith=”CL
   /clr TestApp.cpp”&amp;gt;&lt;br&gt;
   #include &amp;lt;stdio.h&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;#pragma comment(lib, "testlib.lib")&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;__declspec(dllimport) int fUnmanaged();&lt;br&gt;
   __declspec(dllimport) int fManaged();&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;int main()&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; printf("fUnmanaged returns %d\n", fUnmanaged());&lt;br&gt;
   &amp;nbsp; printf("fManaged returns %d\n", fManaged());&lt;br&gt;
   &amp;nbsp; printf("fUnmanaged returns %d\n", fUnmanaged());&lt;br&gt;
   }&lt;br&gt;
   &amp;lt;/code&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   If you start TestApp.exe, you will get the following output:
&lt;/p&gt;
&lt;p&gt;
   fUnmanaged returns 0&lt;br&gt;
   fManaged returns 42&lt;br&gt;
   fUnmanaged returns 42
&lt;/p&gt;
&lt;p&gt;
   The easiest way to avoid these problems is to make sure that files compiled with /clr
   contain only managed code and to leave the native code in cpp files compiled without
   /clr. If you consider using #pragma unmanaged or unmappable C++ constructs in files
   compiled with /clr, you should be aware that all global variables and static member
   variables of that file, are initialized by the module initializer. This is even true
   if the variable is of a native type.
&lt;/p&gt;
&lt;p&gt;
   The compiler's ability to automatically compile a function with unmappable C++ constructs
   to native code can cause a scenario where you get mixed code object files without
   even realizing it. Fortunately a compiler warning C4793 can be emitted in this scenario.
   C4793 is a level 2 warning. To get it, you either have to set the warning level to
   2, or you have to use a compiler switch to make it a level 1 warning, as shown in
   the following code.
&lt;/p&gt;
&lt;p&gt;
   &lt;font face="Courier New"&gt;&amp;lt;code language="C++/CLI" 
   &lt;br&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; filename=" UnmappableConstructs.cpp" 
   &lt;br&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; compileWith="cl /c /clr /w14793 UnmappableConstructs.cpp"&amp;gt;&lt;br&gt;
   void f()&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; __asm int 3;&lt;br&gt;
   }&lt;br&gt;
   &amp;lt;/code&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
   When you compile this code, the C++ compiler will emit the warning C4793 with the
   following message:
&lt;/p&gt;
&lt;p&gt;
   UnmappableConstructs.cpp(3) : warning C4793: '__asm' : causes native code generation
   for function 'void f(void)'&lt;br&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; UnmappableConstructs.cpp(1) : see declaration
   of 'f'&lt;br&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=d5e2c3da-ff4d-40bc-bea9-9da8ec9e091e"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,8d076332-4fb0-44b5-a829-4c4d653de2d6.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,8d076332-4fb0-44b5-a829-4c4d653de2d6.aspx</pingback:target>
      <title>Interesting new feature in .NET: Type identity mapping.</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,8d076332-4fb0-44b5-a829-4c4d653de2d6.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,8d076332-4fb0-44b5-a829-4c4d653de2d6.aspx</link>
      <pubDate>Sat, 26 Nov 2005 11:06:15 GMT</pubDate>
      <description>&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;&lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /&gt;.NET
   has a very interesting new feature regarding type identity. When I tested this feature
   the last time (I think it was with the RC, it did not work, so it is likely you have
   not yet heared about it). But let's start from the beginning:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Type
   identity is a very important concept of a programming infrastructure. In classic C++,
   types are identified by their names. COM uses GUIDs to identitfy types. To achieve
   a strong type safety, type identity in .NET is bound to assembly identity and assembly
   identity can be bound to developers using a public/private key pair. Type identity
   is bound to assembly identity means that 2 types with the same name in two different
   assemblies have two different identities. Assembly identity can be bound to developers
   using a public/private key pair means that developers can&amp;nbsp;use unique public/private
   key pairs to give their assemblies unique and uncloneable names. This also gives all
   types in the assembly unique and uncloneable names.&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;The
   following expression&amp;nbsp;returns a string containing the unique and uncloneable type
   identity, Microsoft has given to the 32 bit signed integer type:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;int::typeid-&amp;gt;AssemblyQualifiedName&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;If
   you are not familiar with the chosen language, the equivalent C# expression would
   be &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;typeof(int).AssemblyQualifiedName&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;.&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;While
   this type identity is very helpful to achieve verifiability, it is also had a drawback:
   This assembly bound type identity ment that a type&amp;nbsp;could not leave the assembly
   where it was defined in without losing it's identity. You can define a type from exactly
   the same code in another assembly, but to the runtime, it would be a different type.
   To understand this, let's have a look at the following example.&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Let's
   assume you have an assembly lib1.dll created from the following code:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;public
   ref class TheType {};&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Let's
   further assume, you have a client application like this one:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;#using
   "lib1.dll"&lt;br&gt;
   int main() {&lt;br&gt;
   &amp;nbsp; using namespace System;&lt;br&gt;
   &amp;nbsp; Console::WriteLine(TheType().GetType()-&amp;gt;AssemblyQualifiedName);&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;&amp;nbsp;
   using System::Reflection::Assembly;&lt;br&gt;
   &amp;nbsp; for each (Assembly^ a in AppDomain::CurrentDomain-&amp;gt;GetAssemblies())&lt;br&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp; Console::WriteLine(a-&amp;gt;FullName); 
   &lt;br&gt;
   }&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Notice
   the elegant way to add an assembly reference inside your code, and the neat alternative
   for creating a temporary object of type TheType - two out of so many reasons why I
   call C++/CLI the &lt;em&gt;&lt;span style="FONT-FAMILY: Verdana"&gt;chosen&lt;/span&gt;&lt;/em&gt; language.&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;If
   you run the application, you will see that TheType is defined in Lib1 and that the
   assemblies mscorlib, app, and lib1 are loaded.&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Let's
   further assume that for the next version, you are&amp;nbsp;redesigning your application
   and you find out, that TheType would now better fit into another assembly. Due to
   the type identity rules I have mentioned, this would mean that TheType would get another
   identity.&amp;nbsp;Therefore this would be a breaking change for lib1.dll: The new version
   of Lib1 would not be backwards compatible with the old one, since it didn't have the
   public type TheType any more.&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Using
   the type identity mapping feature in 2.0, you can reorganize your libraries without
   causing a backwards incompatibility in your new lib1.dll. To&amp;nbsp;explain the mechanics,
   let's assume&amp;nbsp;the source for lib2.dll now contains &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;TheType&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;//lib2.cs&lt;br&gt;
   public ref&amp;nbsp;class TheType {};&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;To
   allow the old version of app.exe to execute even though &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;TheType&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;&amp;nbsp;is
   no longer in the assembly where it is expected (lib1), you&amp;nbsp;can define &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;TheType&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;&amp;nbsp;in
   lib1.dll with a type identity mapping to the type in lib2.dll. These two lines are
   enough to achieve this:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;#using
   "lib2.dll"&lt;br&gt;
   [assembly: TypeForwardedTo(TheType::typeid)];&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Notice
   that this code creates lib1.dll with an assembly depencency to lib2.dll that defines &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;TheType&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;. &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;When
   using this code, the compiler emits the folowing metadata for &lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;TheType&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt; in
   lib1.dll:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;.class
   extern forwarder TheType&lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; .assembly extern lib2&lt;br&gt;
   &amp;nbsp; .class 0x02000002&lt;br&gt;
   }&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;.class
   0x02000002&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt; is
   to the metadata token for TheType in lib2.dll.&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Almost
   the same metadata can be&amp;nbsp;emitted by C#, too; however there is a slight difference:&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;&lt;font face="Courier New"&gt;[assembly:
   System.Runtime.CompilerServices.TypeForwardedTo(typeof(TheType))]&lt;/font&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;C#
   expects you to use the pseudo custom attribute System::Runtime::CompilerServices::TypeForwardedToAttribute,
   whereas C++/CLI uses a compiler-internal attriubte TypeForwardedTo. The philosophies
   of the two languages differ here: C# tries to be consistent in the way attributes
   are used. Regarding attributes,&amp;nbsp;C++/CLI has different roots anyway:&amp;nbsp;.NET
   attributes are, attributed ATL are two examples. Instead of trying to be consistent
   with one or the other attribute model, C++/CLI tries to avoid that the programmer
   has to explicitly use features of the runtime that are intended to be used by compiler
   builders only.&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-GB"&gt;Whatever
   language you use, this simple attribute allows you to reorganize your libraries without
   breaking compatibility with old applications.&lt;/span&gt;&lt;span lang=EN-GB style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: 'Courier New'; mso-ansi-language: EN-GB"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=8d076332-4fb0-44b5-a829-4c4d653de2d6"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,65c852a9-3735-4e48-90c7-8c76003d28c5.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,65c852a9-3735-4e48-90c7-8c76003d28c5.aspx</pingback:target>
      <title>How to use app.config files in Visual C++ 2005 projects</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,65c852a9-3735-4e48-90c7-8c76003d28c5.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,65c852a9-3735-4e48-90c7-8c76003d28c5.aspx</link>
      <pubDate>Fri, 11 Nov 2005 23:34:30 GMT</pubDate>
      <description>&lt;p&gt;
   &lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;&lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /&gt;For
   most Visual Studio .NET language integrations, app.config files are treated specially.
   Before the target application is started, (with or without a debug session), the language
   package ensures that the app.config file is automaticallly copied to the target application's
   configuration file. Visual C++ does not have this feature, however it is easy to get
   the same:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;Add
   a file named app.coinfig to a Visial C++ project and choose the following project
   settings:&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;Command
   line: type app.config &lt;/span&gt;&lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: blue; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;&amp;gt;&lt;/span&gt;&lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt; "$(TargetPath).config"&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;Description:
   "Updating target's configuration file"&lt;/span&gt;&lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: blue; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;Outputs:
   "(TargetPath).config"&lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
   &lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: #003300; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;Notice
   that the file is copied via the command type and piping. I prefer this to using the
   copy command here, sbecause this command ensures that the date of the compiled file
   is automatically adapted whenever the file is copied.&lt;/span&gt;&lt;span lang=EN-US style="FONT-SIZE: 10pt; COLOR: blue; FONT-FAMILY: Verdana; mso-ansi-language: EN-US"&gt;
   &lt;o:p&gt;&lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="MARGIN: 0cm 0cm 0pt"&gt;
   &lt;span lang=EN-US style="mso-ansi-language: EN-US"&gt;
   &lt;o:p&gt;
      &lt;font face="Times New Roman" color=#000000 size=3&gt;&amp;nbsp;&lt;/font&gt;
   &lt;/o:p&gt;
   &lt;/span&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=65c852a9-3735-4e48-90c7-8c76003d28c5"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,48daf2ff-41c8-4312-9d80-bdfa8c55058d.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,48daf2ff-41c8-4312-9d80-bdfa8c55058d.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      On <a href="news:microsoft.public.dotnet.languages.vc">microsoft.public.dotnet.languages.vc</a>,
      bonk has asked this interesting question. This blog entry gives you a simple example
      and explains why this is possible. In further blogs I will discuss when this
      can be dangerous.
   </p>
        <p>
      Your idea is possible, but there may be some issues. Let's start with a simple sample
   </p>
        <p>
      &lt;code language="CPPCLI" file="test.cpp" compileWith="CL /LD /clr test.cpp"&gt;<br />
      // pragma managed is the default 
      <br />
      extern "C" __declspec(dllexport) void __stdcall f() 
      <br />
      {<br />
        System::Console::WriteLine("I am f(), a managed function that test.dll exports
      to native clients");<br />
      }<br />
      &lt;/code&gt;
   </p>
        <p>
      "dumpbin /exports test.dll" will show you that there is indeed a native exported function:
   </p>
        <p>
          ordinal hint RVA      name
   </p>
        <p>
                1    0 00001020
      _f@0
   </p>
        <p>
      What is going on here? How can unmanaged code can call managed code?
   </p>
        <p>
      To answer this question, let's have a look at a simple application that calls managed
      code from unmanaged code:
   </p>
        <p>
      &lt;code language="CPPCLI" file="testApp.cpp" compileWith="CL /clr testapp.cpp"&gt;<br />
      void f() 
      <br />
      {<br />
        System::Console::WriteLine("I am f(), a managed function that can be called
      by native clients");<br />
      }
   </p>
        <p>
      void f2() 
      <br />
      {<br />
        System::Console::WriteLine("I am f2(), a managed function that can be called
      by native clients");<br />
      }
   </p>
        <p>
      #pragma unmanaged<br />
      int main() {<br />
        f();<br />
        f2();<br />
      }<br />
      &lt;/code&gt;
   </p>
        <p>
      The native function main can not call f  without some magic that is going on
      under the hood: Think of a scenario, where f has not even been jit compiled. On the
      one hand, the call "f()" is compiled to a call to an address local to the exe file,
      on the other hand, the code that should really be executed, is JIT compiled. So what
      is going on here?
   </p>
        <p>
      "f()" and "f2()" are indeed calls a local addresses. This is an excerpt from the disassembly
      window:
   </p>
        <p>
        f();<br />
      00401053  call        f (401030h) 
      <br />
        f2();<br />
      00401058  call        f2 (401040h) 
   </p>
        <p>
      Notice that the calling addresses (00401053) and the called addresses (401030) are
      both belong to testApp.exe's code.
   </p>
        <p>
      Here is what the disassembly window tells us about the called addresses:
   </p>
        <p>
      f:<br />
      00401030  jmp         dword ptr [__mep@?f@@$$FYAXXZ
      (409000h)] 
   </p>
        <p>
      f2:<br />
      00401040  jmp         dword ptr [__mep@?f2@@$$FYAXXZ
      (409004h)] 
   </p>
        <p>
      "jmp dword ptr [...x...]" is an indirect jump. It means: at the address ...x..., is
      the address the address you have to jump to.
   </p>
        <p>
      Here is what these addresses are in my debugger's memory window:<br />
      0x00409000:  00 CB 00 12<br />
      0x00409004:  00 CB 00 4E
   </p>
        <p>
      Both addresses are far away from testApp.exe's base address, so they are clearly outside
      testApp's code. This is runtime generated code, but we have not yet reached JIT compiled
      code. What we see here are runtime generated unmanaged -&gt; managed thunks. These
      thunks perform the managed / unmanaged transition call the managed functions (f, or
      f2) in the end.
   </p>
        <p>
      As I have mentioned, these functions are runtime generated: How does the runtime know
      that at address 0x00409000 should be a pointer to the unmanaged -&gt; managed thunk
      for f() and at address 0x00409004 should be a pointer to the thunk for f2()?
   </p>
        <p>
      Well the new linker is much smarter than you may expect: The linker generates .NET
      metadata that tells the runtime exactly that! If you view testApp.exe in ILDASM and
      inspect the assembly's manifest, you will find so called vtFixups at the end of the
      manifest. Here is an expert:
   </p>
        <p>
      .imagebase 0x00400000<br />
      .subsystem 0x0003       // WINDOWS_CUI<br />
      .corflags 0x00000000<br />
      .vtfixup [1] int32 retainappdomain at D_00009000 // 06000001<br />
      .vtfixup [1] int32 retainappdomain at D_00009004 // 06000002<br />
      ...many other vtfixups elided for clarity here ...
   </p>
        <p>
      Note that these lines contain familiar numbers: 00009000 and 00009004. If you add
      the .imagebase to these numbers, you will get:
   </p>
        <p>
      00409000 and 00409004. Does this ring the bell? Using these addresses, the compiled
      code finds the managed -&gt; unmanaged thunks.
   </p>
        <p>
      So what is the other part of the vtfixup 06000001 and 06000002?
   </p>
        <p>
      Well these are metadata tokens. Metadata starting with the 06 are always method tokens
      and now it is not very difficult to guess what is going on: 06000001 is the metadata
      token for the managed function f() and 06000002 is the metatdata token for f2(). You
      can prove this by adding the following code to f() and f2():
   </p>
        <p>
      System::Console::WriteLine("{0:x8}", (gcnew System::Diagnostics::StackTrace())-&gt;GetFrame(0)-&gt;GetMethod()-&gt;MetadataToken);
   </p>
        <p>
      The .vtfixup metadata tells the runtime: 
      <br />
      When the assembly is loaded:<br />
        Generate a unmanaged-&gt;managed thunk for the method f() and store a pointer
      to it in 00409000 and<br />
        generate another unmanaged-&gt;managed thunk for method f2() and store a pointer
      to it in 00409004.
   </p>
        <p>
      Since this is done, the unmanaged function main can call the managed functions f and
      f2 as if they were native functions.
   </p>
        <p>
      In the testApp.exe sample there is a simplification, that is not true for the test.dll
      I have disused right at the beginning: Since testApp.exe is an exe it is guaranteed
      that the CLR has been initialized already. (The CLR will be initialized automatically
      when the EXE application starts.) This assumption is not true for managed functions
      exported via DLLs: The DLL's client may be a native client. To handle this case, a
      small stub is exported. This small stub ensures that the CLR is initialized properly
      and that the assembly is loaded properly into the default appdomain, before the unmanaged
      -&gt; managed stub is called. This is often called delayed CLR initialization.
   </p>
        <p>
      Although all this sounds nice there are still some things to discuss:
   </p>
        <p>
      * Issues when combining exported managed functions with #pragma managed
   </p>
        <p>
      * Turning the generation of managed / unmanaged thunks off in cases where they are
      not needed
   </p>
        <p>
      * What happens if managed code calls a managed entry point via P/Invoke?
   </p>
        <p>
      I hope I will find some time to discuss these things in the next days.
   </p>
        <p>
       
   </p>
        <img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=48daf2ff-41c8-4312-9d80-bdfa8c55058d" />
      </body>
      <title>Can DLLs export managed functions to native clients?</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,48daf2ff-41c8-4312-9d80-bdfa8c55058d.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,48daf2ff-41c8-4312-9d80-bdfa8c55058d.aspx</link>
      <pubDate>Wed, 19 Oct 2005 21:58:59 GMT</pubDate>
      <description>&lt;p&gt;
   On &lt;a href="news:microsoft.public.dotnet.languages.vc"&gt;microsoft.public.dotnet.languages.vc&lt;/a&gt;,
   bonk has asked this interesting question. This blog entry gives you a simple example
   and explains why this is possible. In further blogs I will&amp;nbsp;discuss when this
   can be dangerous.
&lt;/p&gt;
&lt;p&gt;
   Your idea is possible, but there may be some issues. Let's start with a simple sample
&lt;/p&gt;
&lt;p&gt;
   &amp;lt;code language="CPPCLI" file="test.cpp" compileWith="CL /LD /clr test.cpp"&amp;gt;&lt;br&gt;
   // pragma managed is the default 
   &lt;br&gt;
   extern "C" __declspec(dllexport) void __stdcall f() 
   &lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; System::Console::WriteLine("I am f(), a managed function that test.dll exports
   to native clients");&lt;br&gt;
   }&lt;br&gt;
   &amp;lt;/code&amp;gt;
&lt;/p&gt;
&lt;p&gt;
   "dumpbin /exports test.dll" will show you that there is indeed a native exported function:
&lt;/p&gt;
&lt;p&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp; ordinal hint RVA&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name
&lt;/p&gt;
&lt;p&gt;
   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1&amp;nbsp;&amp;nbsp;&amp;nbsp; 0 00001020
   _f@0
&lt;/p&gt;
&lt;p&gt;
   What is going on here? How can unmanaged code can call managed code?
&lt;/p&gt;
&lt;p&gt;
   To answer this question, let's have a look at a simple application that calls managed
   code from unmanaged code:
&lt;/p&gt;
&lt;p&gt;
   &amp;lt;code language="CPPCLI" file="testApp.cpp" compileWith="CL /clr testapp.cpp"&amp;gt;&lt;br&gt;
   void f() 
   &lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; System::Console::WriteLine("I am f(), a managed function that can be called
   by native clients");&lt;br&gt;
   }
&lt;/p&gt;
&lt;p&gt;
   void f2() 
   &lt;br&gt;
   {&lt;br&gt;
   &amp;nbsp; System::Console::WriteLine("I am f2(), a managed function that can be called
   by native clients");&lt;br&gt;
   }
&lt;/p&gt;
&lt;p&gt;
   #pragma unmanaged&lt;br&gt;
   int main() {&lt;br&gt;
   &amp;nbsp; f();&lt;br&gt;
   &amp;nbsp; f2();&lt;br&gt;
   }&lt;br&gt;
   &amp;lt;/code&amp;gt;
&lt;/p&gt;
&lt;p&gt;
   The native function main can not call f&amp;nbsp; without some magic that is going on
   under the hood: Think of a scenario, where f has not even been jit compiled. On the
   one hand, the call "f()" is compiled to a call to an address local to the exe file,
   on the other hand, the code that should really be executed, is JIT compiled. So what
   is going on here?
&lt;/p&gt;
&lt;p&gt;
   "f()" and "f2()" are indeed calls a local addresses. This is an excerpt from the disassembly
   window:
&lt;/p&gt;
&lt;p&gt;
   &amp;nbsp; f();&lt;br&gt;
   00401053&amp;nbsp; call&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; f (401030h) 
   &lt;br&gt;
   &amp;nbsp; f2();&lt;br&gt;
   00401058&amp;nbsp; call&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; f2 (401040h) 
&lt;/p&gt;
&lt;p&gt;
   Notice that the calling addresses (00401053) and the called addresses (401030) are
   both belong to testApp.exe's code.
&lt;/p&gt;
&lt;p&gt;
   Here is what the disassembly window tells us about the called addresses:
&lt;/p&gt;
&lt;p&gt;
   f:&lt;br&gt;
   00401030&amp;nbsp; jmp&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dword ptr [__mep@?f@@$$FYAXXZ
   (409000h)] 
&lt;/p&gt;
&lt;p&gt;
   f2:&lt;br&gt;
   00401040&amp;nbsp; jmp&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dword ptr [__mep@?f2@@$$FYAXXZ
   (409004h)] 
&lt;/p&gt;
&lt;p&gt;
   "jmp dword ptr [...x...]" is an indirect jump. It means: at the address ...x..., is
   the address the address you have to jump to.
&lt;/p&gt;
&lt;p&gt;
   Here is what these addresses are in my debugger's memory window:&lt;br&gt;
   0x00409000:&amp;nbsp; 00 CB 00 12&lt;br&gt;
   0x00409004:&amp;nbsp; 00 CB 00 4E
&lt;/p&gt;
&lt;p&gt;
   Both addresses are far away from testApp.exe's base address, so they are clearly outside
   testApp's code. This is runtime generated code, but we have not yet reached JIT compiled
   code. What we see here are runtime generated unmanaged -&amp;gt; managed thunks. These
   thunks perform the managed / unmanaged transition call the managed functions (f, or
   f2) in the end.
&lt;/p&gt;
&lt;p&gt;
   As I have mentioned, these functions are runtime generated: How does the runtime know
   that at address 0x00409000 should be a pointer to the unmanaged -&amp;gt; managed thunk
   for f() and at address 0x00409004 should be a pointer to the thunk for f2()?
&lt;/p&gt;
&lt;p&gt;
   Well the new linker is much smarter than you may expect: The linker generates .NET
   metadata that tells the runtime exactly that! If you view testApp.exe in ILDASM and
   inspect the assembly's manifest, you will find so called vtFixups at the end of the
   manifest. Here is an expert:
&lt;/p&gt;
&lt;p&gt;
   .imagebase 0x00400000&lt;br&gt;
   .subsystem 0x0003&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // WINDOWS_CUI&lt;br&gt;
   .corflags 0x00000000&lt;br&gt;
   .vtfixup [1] int32 retainappdomain at D_00009000 // 06000001&lt;br&gt;
   .vtfixup [1] int32 retainappdomain at D_00009004 // 06000002&lt;br&gt;
   ...many other vtfixups elided for clarity here ...
&lt;/p&gt;
&lt;p&gt;
   Note that these lines contain familiar numbers: 00009000 and 00009004. If you add
   the .imagebase to these numbers, you will get:
&lt;/p&gt;
&lt;p&gt;
   00409000 and 00409004. Does this ring the bell? Using these addresses, the compiled
   code finds the managed -&amp;gt; unmanaged thunks.
&lt;/p&gt;
&lt;p&gt;
   So what is the other part of the vtfixup 06000001 and 06000002?
&lt;/p&gt;
&lt;p&gt;
   Well these are metadata tokens. Metadata starting with the 06 are always method tokens
   and now it is not very difficult to guess what is going on: 06000001 is the metadata
   token for the managed function f() and 06000002 is the metatdata token for f2(). You
   can prove this by adding the following code to f() and f2():
&lt;/p&gt;
&lt;p&gt;
   System::Console::WriteLine("{0:x8}", (gcnew System::Diagnostics::StackTrace())-&amp;gt;GetFrame(0)-&amp;gt;GetMethod()-&amp;gt;MetadataToken);
&lt;/p&gt;
&lt;p&gt;
   The .vtfixup metadata tells the runtime: 
   &lt;br&gt;
   When the assembly is loaded:&lt;br&gt;
   &amp;nbsp; Generate a unmanaged-&amp;gt;managed thunk for the method f() and store a pointer
   to it in 00409000 and&lt;br&gt;
   &amp;nbsp; generate another unmanaged-&amp;gt;managed thunk for method f2() and store a pointer
   to it in 00409004.
&lt;/p&gt;
&lt;p&gt;
   Since this is done, the unmanaged function main can call the managed functions f and
   f2 as if they were native functions.
&lt;/p&gt;
&lt;p&gt;
   In the testApp.exe sample there is a simplification, that is not true for the test.dll
   I have disused right at the beginning: Since testApp.exe is an exe it is guaranteed
   that the CLR has been initialized already. (The CLR will be initialized automatically
   when the EXE application starts.) This assumption is not true for managed functions
   exported via DLLs: The DLL's client may be a native client. To handle this case, a
   small stub is exported. This small stub ensures that the CLR is initialized properly
   and that the assembly is loaded properly into the default appdomain, before the unmanaged
   -&amp;gt; managed stub is called. This is often called delayed CLR initialization.
&lt;/p&gt;
&lt;p&gt;
   Although all this sounds nice there are still some things to discuss:
&lt;/p&gt;
&lt;p&gt;
   * Issues when combining exported managed functions with #pragma managed
&lt;/p&gt;
&lt;p&gt;
   * Turning the generation of managed / unmanaged thunks off in cases where they are
   not needed
&lt;/p&gt;
&lt;p&gt;
   * What happens if&amp;nbsp;managed code calls a managed entry point via P/Invoke?
&lt;/p&gt;
&lt;p&gt;
   I hope I will find some time to discuss these things in the next days.
&lt;/p&gt;
&lt;p&gt;
   &amp;nbsp;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=48daf2ff-41c8-4312-9d80-bdfa8c55058d"&gt;</description>
    </item>
    <item>
      <trackback:ping>http://www.heege.net/blog/Trackback,guid,e998baf7-390f-4d59-bbd1-fc5c1adbec2f.aspx</trackback:ping>
      <pingback:server>http://www.heege.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.heege.net/blog/PermaLink,guid,e998baf7-390f-4d59-bbd1-fc5c1adbec2f.aspx</pingback:target>
      <body xmlns="http://www.w3.org/1999/xhtml">A long time of research will come
   to an end soon. I have spent the last months writing the <a href="http://www.develop.com/training/course.aspx?id=323">Essential
   C++/CLI class</a> for <a href="http://www.develop.com/">DevelopMentor</a>. I still
   have 8 labs to write and some slides need a redesign, but at least I am able to spend
   some time sharing important details about C++/CLI, "It Just Works", and .NET in General.<img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=e998baf7-390f-4d59-bbd1-fc5c1adbec2f" /></body>
      <title>My Essential C++/CLI Seminar</title>
      <guid>http://www.heege.net/blog/PermaLink,guid,e998baf7-390f-4d59-bbd1-fc5c1adbec2f.aspx</guid>
      <link>http://www.heege.net/blog/PermaLink,guid,e998baf7-390f-4d59-bbd1-fc5c1adbec2f.aspx</link>
      <pubDate>Wed, 19 Oct 2005 20:39:05 GMT</pubDate>
      <description>A long time of research&amp;nbsp;will come to an end soon. I have spent the last months writing the &lt;a href="http://www.develop.com/training/course.aspx?id=323"&gt;Essential
C++/CLI class&lt;/a&gt; for &lt;a href="http://www.develop.com/"&gt;DevelopMentor&lt;/a&gt;. I still
have 8 labs to write and some slides need a redesign, but at least I am able to spend
some time sharing important details about C++/CLI, "It Just Works", and .NET in General.&lt;img width="0" height="0" src="http://www.heege.net/blog/aggbug.ashx?id=e998baf7-390f-4d59-bbd1-fc5c1adbec2f"&gt;</description>
    </item>
  </channel>
</rss>