<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Damir's Corner - Development|Interop</title>
    <link>http://www.damirscorner.com/</link>
    <description>Notes from Daily Encounters with Technology</description>
    <language>en-us</language>
    <copyright>Damir Arh, M. Sc.</copyright>
    <lastBuildDate>Tue, 29 Apr 2008 13:29:08 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>damir.arh@gmail.com</managingEditor>
    <webMaster>damir.arh@gmail.com</webMaster>
    <item>
      <trackback:ping>http://www.damirscorner.com/Trackback.aspx?guid=84c751f7-f67e-47f0-9def-3035b5333cf5</trackback:ping>
      <pingback:server>http://www.damirscorner.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.damirscorner.com/PermaLink,guid,84c751f7-f67e-47f0-9def-3035b5333cf5.aspx</pingback:target>
      <dc:creator>Damir Arh</dc:creator>
      <wfw:comment>http://www.damirscorner.com/CommentView,guid,84c751f7-f67e-47f0-9def-3035b5333cf5.aspx</wfw:comment>
      <wfw:commentRss>http://www.damirscorner.com/SyndicationService.asmx/GetEntryCommentsRss?guid=84c751f7-f67e-47f0-9def-3035b5333cf5</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A .NET application in the company I work for recently started crashing under Windows
Vista when trying to open a window implemented in an ActiveX DLL. Investigations showed
that they were caused by an <font face="Courier New">AccessViolationException "Attempted
to read or write protected memory. This is often an indication that other memory is
corrupt."</font>. The cause was one of the ActiveX controls in the window. When instantited
directly in a .NET Form the exception above was contained in a <font face="Courier New">TargetInvocationException
"Unable to get the window handle for the '&lt;control name&gt;' control. Windowless
ActiveX controls are not supported."</font>. Knowing that the control didn't suddenly
turn windowless we dug deeper.
</p>
        <p>
It turned out that the problem appeared with .NET Framework 2.0 Service Pack 1. <a href="http://blogs.msdn.com/ed_maurer/archive/2007/12/14/nxcompat-and-the-c-compiler.aspx">Apparently</a> it
caused the C# compiler in Visual Studio 2005 and later to set the <font face="Courier New">NXCOMPAT</font> bit
for all build targets without an option to turn this new behavior off. For those who
don't know, this means that DEP (data execution prevention) will kick in unless it
is turned off completely in the operating system. This wouldn't be a big deal unless
ATL before Visual Studio 2005 didn't have a <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=299397">bug</a> which
caused the heap allocated memory not to be flagged as executable, which under the
new circumstances results as the already mentioned exception. Windows XP has DEP turned
off by default therefore everything still works but in Windows Vista it is turned
on and prevents such application from functioning properly.
</p>
        <p>
The best solution would of course be to recompile the ActiveX controls in Visual Studio
2005 or later but this might not be possible if they are supplied by a third party.
In this case the most obvious approach to dealing with the situation is to disable
DEP in Vista. There is a <font face="Courier New">Data Execution Prevention</font> tab
in the <font face="Courier New">Performance Options</font> which open when you click
the <font face="Courier New">Settings</font> button in the <font face="Courier New">Performance</font> frame
of the <font face="Courier New">Advanced</font> tab in the <font face="Courier New">System
Properties</font> dialog but it only allows switching between DEP for all processes
with defined exceptions and DEP for essential Windows programs and services, i.e.
executables flagged with the <font face="Courier New">NXCOMPAT</font> bit. The only
way to turn DEP completely off is executing the following command with administrative
privileges:
</p>
        <p>
          <font face="Courier New">bcdedit.exe /set {current} nx AlwaysOff</font>
        </p>
        <p>
After restart DEP will be turned off and problematic binaries will work once again.
To restore the previous (default) state replace <font face="Courier New">AlwaysOff</font> with <font face="Courier New">OptIn</font>.
The <font face="Courier New">AlwaysOn</font> option enables DEP for all processes
and might cause additional problems (e.g. Google Calendar Sync in its current version
0.9.3.2 doesn't work in this mode).
</p>
        <p>
Unfortunately, this solution would require all your Vista using customers to disable
DEP as well which really isn't an option for commercial software. Fortunately, there
is another solution. Although there is no compiler option to turn keep the <font face="Courier New">NXCOMPAT</font> bit
unset, you can still do this after compilation using the <font face="Courier New">editbin.exe</font> which
comes with C++ compiler for Visual Studio 2005 and later:
</p>
        <p>
          <font face="Courier New">editbin.exe /NXCOMPAT:NO &lt;filename.exe&gt;</font>
        </p>
        <p>
This command removes the <font face="Courier New">NXCOMPAT</font> bit and restores
the behavior before .NET 2.0 SP1. If your assembly was signed it also invalidates
the signature so you'll have to resign it:
</p>
        <p>
          <font face="Courier New">sn.exe -R &lt;filename.exe&gt; &lt;keyfile.snk&gt;</font>
        </p>
        <p>
You can automate this by putting the two commands in the <font face="Courier New">Post-build
event command line</font> for the project:
</p>
        <p>
          <font face="Courier New">editbin.exe /NXCOMPAT:NO "$(TargetPath)"<br />
sn.exe -R "$(TargetPath)" "$(ProjectDir)&lt;keyfile.snk&gt;"</font>
        </p>
        <p>
You might need to call <font face="Courier New">vcvars32.bat</font> before that to
put the required executables in path and enable <font face="Courier New">editbin.exe</font> dependencies
to be resolved. Note that in a completely automated build scenario using <font face="Courier New">MSBuild</font> you'll
have to specify full path for the <font face="Courier New">vcvars32.bat</font> because <font face="Courier New">$(DevEnvDir)</font> resolves
to <font face="Courier New">*Undefined*</font> outside Visual Studio 2005. Also your
strong name key should be in a <font face="Courier New">snk</font> file instead of
a password protected <font face="Courier New">pfx</font> file because <font face="Courier New">sn.exe</font><a href="http://blogs.msdn.com/shawnfa/archive/2006/02/14/531921.aspx">doesn't
allow</a> the password to be read from a redirected standard input.
</p>
        <img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=84c751f7-f67e-47f0-9def-3035b5333cf5" />
      </body>
      <title>Old ActiveX controls under .NET 2.0 SP1</title>
      <guid isPermaLink="false">http://www.damirscorner.com/PermaLink,guid,84c751f7-f67e-47f0-9def-3035b5333cf5.aspx</guid>
      <link>http://www.damirscorner.com/OldActiveXControlsUnderNET20SP1.aspx</link>
      <pubDate>Tue, 29 Apr 2008 13:29:08 GMT</pubDate>
      <description>&lt;p&gt;
A .NET application in the company I work for recently started crashing under Windows
Vista when trying to open a window implemented in an ActiveX DLL. Investigations showed
that they were caused by an &lt;font face="Courier New"&gt;AccessViolationException "Attempted
to read or write protected memory. This is often an indication that other memory is
corrupt."&lt;/font&gt;. The cause was one of the ActiveX controls in the window. When instantited
directly in a .NET Form the exception above was contained in a &lt;font face="Courier New"&gt;TargetInvocationException
"Unable to get the window handle for the '&amp;lt;control name&amp;gt;' control. Windowless
ActiveX controls are not supported."&lt;/font&gt;. Knowing that the control didn't suddenly
turn windowless we dug deeper.
&lt;/p&gt;
&lt;p&gt;
It turned out that the problem appeared with .NET Framework 2.0 Service Pack 1. &lt;a href="http://blogs.msdn.com/ed_maurer/archive/2007/12/14/nxcompat-and-the-c-compiler.aspx"&gt;Apparently&lt;/a&gt; it
caused the C# compiler in Visual Studio 2005 and later to set the &lt;font face="Courier New"&gt;NXCOMPAT&lt;/font&gt; bit
for all build targets without an option to turn this new behavior off. For those who
don't know, this means that DEP (data execution prevention) will kick in unless it
is turned off completely in the operating system. This wouldn't be a big deal unless
ATL before Visual Studio 2005 didn't have a &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=299397"&gt;bug&lt;/a&gt; which
caused the heap allocated memory not to be flagged as executable, which under the
new circumstances results as the already mentioned exception. Windows XP has DEP turned
off by default therefore everything still works but in Windows Vista it is turned
on and prevents such application from functioning properly.
&lt;/p&gt;
&lt;p&gt;
The best solution would of course be to recompile the ActiveX controls in Visual Studio
2005 or later but this might not be possible if they are supplied by a third party.
In this case the most obvious approach to dealing with the situation is to disable
DEP in Vista. There is a &lt;font face="Courier New"&gt;Data Execution Prevention&lt;/font&gt; tab
in the &lt;font face="Courier New"&gt;Performance Options&lt;/font&gt; which open when you click
the &lt;font face="Courier New"&gt;Settings&lt;/font&gt; button in the &lt;font face="Courier New"&gt;Performance&lt;/font&gt; frame
of the &lt;font face="Courier New"&gt;Advanced&lt;/font&gt; tab in the &lt;font face="Courier New"&gt;System
Properties&lt;/font&gt; dialog but it only allows switching between DEP for all processes
with defined exceptions and DEP for essential Windows programs and services, i.e.
executables flagged with the &lt;font face="Courier New"&gt;NXCOMPAT&lt;/font&gt; bit. The only
way to turn DEP completely off is executing the following command with administrative
privileges:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;bcdedit.exe /set {current} nx AlwaysOff&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
After restart DEP will be turned off and problematic binaries will work once again.
To restore the previous (default) state replace &lt;font face="Courier New"&gt;AlwaysOff&lt;/font&gt; with &lt;font face="Courier New"&gt;OptIn&lt;/font&gt;.
The &lt;font face="Courier New"&gt;AlwaysOn&lt;/font&gt; option enables DEP for all processes
and might cause additional problems (e.g. Google Calendar Sync in its current version
0.9.3.2 doesn't work in this mode).
&lt;/p&gt;
&lt;p&gt;
Unfortunately, this solution would require all your Vista using customers to disable
DEP as well which really isn't an option for commercial software. Fortunately, there
is another solution. Although there is no compiler option to turn keep the &lt;font face="Courier New"&gt;NXCOMPAT&lt;/font&gt; bit
unset, you can still do this after compilation using the &lt;font face="Courier New"&gt;editbin.exe&lt;/font&gt; which
comes with C++ compiler for Visual Studio 2005 and later:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;editbin.exe /NXCOMPAT:NO &amp;lt;filename.exe&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
This command removes the &lt;font face="Courier New"&gt;NXCOMPAT&lt;/font&gt; bit and restores
the behavior before .NET 2.0 SP1. If your assembly was signed it also invalidates
the signature so you'll have to resign it:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;sn.exe -R &amp;lt;filename.exe&amp;gt; &amp;lt;keyfile.snk&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
You can automate this by putting the two commands in the &lt;font face="Courier New"&gt;Post-build
event command line&lt;/font&gt; for the project:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;editbin.exe /NXCOMPAT:NO "$(TargetPath)"&lt;br&gt;
sn.exe -R "$(TargetPath)" "$(ProjectDir)&amp;lt;keyfile.snk&amp;gt;"&lt;/font&gt; 
&lt;/p&gt;
&lt;p&gt;
You might need to call &lt;font face="Courier New"&gt;vcvars32.bat&lt;/font&gt; before that to
put the required executables in path and enable &lt;font face="Courier New"&gt;editbin.exe&lt;/font&gt; dependencies
to be resolved. Note that in a completely automated build scenario using &lt;font face="Courier New"&gt;MSBuild&lt;/font&gt; you'll
have to specify full path for the &lt;font face="Courier New"&gt;vcvars32.bat&lt;/font&gt; because &lt;font face="Courier New"&gt;$(DevEnvDir)&lt;/font&gt; resolves
to &lt;font face="Courier New"&gt;*Undefined*&lt;/font&gt; outside Visual Studio 2005. Also your
strong name key should be in a &lt;font face="Courier New"&gt;snk&lt;/font&gt; file instead of
a password protected &lt;font face="Courier New"&gt;pfx&lt;/font&gt; file because &lt;font face="Courier New"&gt;sn.exe&lt;/font&gt; &lt;a href="http://blogs.msdn.com/shawnfa/archive/2006/02/14/531921.aspx"&gt;doesn't
allow&lt;/a&gt; the password to be read from a redirected standard input.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=84c751f7-f67e-47f0-9def-3035b5333cf5" /&gt;</description>
      <comments>http://www.damirscorner.com/CommentView,guid,84c751f7-f67e-47f0-9def-3035b5333cf5.aspx</comments>
      <category>Development</category>
      <category>Development/.NET</category>
      <category>Development/Interop</category>
    </item>
    <item>
      <trackback:ping>http://www.damirscorner.com/Trackback.aspx?guid=330dfd2e-d438-41fb-ae74-1bafc8ca9076</trackback:ping>
      <pingback:server>http://www.damirscorner.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.damirscorner.com/PermaLink,guid,330dfd2e-d438-41fb-ae74-1bafc8ca9076.aspx</pingback:target>
      <dc:creator>Damir Arh</dc:creator>
      <wfw:comment>http://www.damirscorner.com/CommentView,guid,330dfd2e-d438-41fb-ae74-1bafc8ca9076.aspx</wfw:comment>
      <wfw:commentRss>http://www.damirscorner.com/SyndicationService.asmx/GetEntryCommentsRss?guid=330dfd2e-d438-41fb-ae74-1bafc8ca9076</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
By switching from <a href="http://www.damirscorner.com/blog/UsefulPInvokeResources.aspx">C#
with P/Invoke calls</a> to <a href="http://www.damirscorner.com/blog/ImplementingAManagedInterfaceInC.aspx">Managed
C++</a> when implementing a managed wrapper for the ANSI C style library I stumbled
upon, I wanted to avoid the tedious and error-prone task of writing the P/Invoke signatures
for function calls and user-defined types for the structures they used. As a side
result I also managed to avoid most of the advanced marshalling issues with complex
data structures.
</p>
        <p>
With simple value types not needing any explicit marshalling only strings need special
attention since <font face="Courier New">char*</font> and <font face="Courier New">System::String</font> can’t
be implicitly converted between. The <font face="Courier New">Marshal</font> class
implements the methods necessary for doing this as demonstrated in the following snippet:
</p>
        <p>
          <font face="Courier New">String^ MCPP::Together(String^ first, String^ second)<br />
{<br />
   // marshal managed strings to unamanged memory 
<br />
   IntPtr firstPtr = Marshal::StringToHGlobalAnsi(first);<br />
   IntPtr secondPtr = Marshal::StringToHGlobalAnsi(second);</font>
        </p>
        <p>
          <font face="Courier New">   // cast unmanaged buffer to a characer array<br />
   char* firstNative = static_cast&lt;char*&gt;(firstPtr.ToPointer());<br />
   char* secondNative = static_cast&lt;char*&gt;(secondPtr.ToPointer());</font>
        </p>
        <p>
          <font face="Courier New">   // perform some unmanaged calls<br />
   int bufferSize = strlen(firstNative) + strlen(secondNative) + 4;<br />
   char* resultBuffer = new char[bufferSize];<br />
   sprintf_s(resultBuffer, bufferSize, "%s + %s", firstNative, secondNative);<br />
   
<br />
   // marshal unmanaged character array to managed string<br />
   String^ result = Marshal::PtrToStringAnsi(static_cast&lt;IntPtr&gt;(resultBuffer));<br />
   
<br />
   // free all unmanaged buffers<br />
   delete[] resultBuffer;<br />
   Marshal::FreeHGlobal(firstPtr);<br />
   Marshal::FreeHGlobal(secondPtr);<br />
   
<br />
   // return managed string<br />
   return result;<br />
}</font>
        </p>
        <p>
It should be noted that it wouldn’t make any sense switching to unmanaged code to
do some string operations only as shown above. This is for demonstration purposes
only and you would usually call some unmanaged libraries or the like instead of it.
But it is a nice demonstration how cumbersome string operations were in C. If you
were doing this once, the <font face="Courier New">sprintf_s</font> function call
might have caught your attention. It’s a <a href="http://msdn2.microsoft.com/en-us/library/ms235384.aspx">safe
implementation</a> of <font face="Courier New">sprintf</font> which prevents buffer
overflows.
</p>
        <p>
Another point worth mentioning is that you have to take care of allocated memory for
the conversion since your character array is now allocated on the unmanaged heap.
Make sure you use the <font face="Courier New">FreeHGlobal</font> method to do it,
not the <font face="Courier New">free</font> (used for freeing memory allocated by <font face="Courier New">*alloc</font> calls
– ANSI C style) or <font face="Courier New">delete</font> (used for freeing memory
allocated by <font face="Courier New">new</font> calls – C++ style) functions.
</p>
        <p>
To reduce the code overhead of string conversions between managed and unmanaged world
you might consider wrapping it into a <a href="http://blogs.msdn.com/jeremykuhne/archive/2005/06/11/428363.aspx">helper
class</a>. This should also help preventing unwanted memory leaks during the conversions.
</p>
        <img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=330dfd2e-d438-41fb-ae74-1bafc8ca9076" />
      </body>
      <title>Marshalling System.String to char* and vice-versa</title>
      <guid isPermaLink="false">http://www.damirscorner.com/PermaLink,guid,330dfd2e-d438-41fb-ae74-1bafc8ca9076.aspx</guid>
      <link>http://www.damirscorner.com/MarshallingSystemStringToCharAndViceversa.aspx</link>
      <pubDate>Sun, 28 May 2006 12:41:03 GMT</pubDate>
      <description>&lt;p&gt;
By switching from &lt;a href="http://www.damirscorner.com/blog/UsefulPInvokeResources.aspx"&gt;C#
with P/Invoke calls&lt;/a&gt;&amp;nbsp;to &lt;a href="http://www.damirscorner.com/blog/ImplementingAManagedInterfaceInC.aspx"&gt;Managed
C++&lt;/a&gt;&amp;nbsp;when implementing a managed wrapper for the ANSI C style library I stumbled
upon, I wanted to avoid the tedious and error-prone task of writing the P/Invoke signatures
for function calls and user-defined types for the structures they used. As a side
result I also managed to avoid most of the advanced marshalling issues with complex
data structures.
&lt;/p&gt;
&lt;p&gt;
With simple value types not needing any explicit marshalling only strings need special
attention since &lt;font face="Courier New"&gt;char*&lt;/font&gt; and &lt;font face="Courier New"&gt;System::String&lt;/font&gt; can’t
be implicitly converted between. The &lt;font face="Courier New"&gt;Marshal&lt;/font&gt; class
implements the methods necessary for doing this as demonstrated in the following snippet:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;String^ MCPP::Together(String^ first, String^ second)&lt;br&gt;
{&lt;br&gt;
&amp;nbsp;&amp;nbsp; // marshal managed strings to unamanged memory 
&lt;br&gt;
&amp;nbsp;&amp;nbsp; IntPtr firstPtr = Marshal::StringToHGlobalAnsi(first);&lt;br&gt;
&amp;nbsp;&amp;nbsp; IntPtr secondPtr = Marshal::StringToHGlobalAnsi(second);&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp; // cast unmanaged buffer to a characer array&lt;br&gt;
&amp;nbsp;&amp;nbsp; char* firstNative = static_cast&amp;lt;char*&amp;gt;(firstPtr.ToPointer());&lt;br&gt;
&amp;nbsp;&amp;nbsp; char* secondNative = static_cast&amp;lt;char*&amp;gt;(secondPtr.ToPointer());&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp; // perform some unmanaged calls&lt;br&gt;
&amp;nbsp;&amp;nbsp; int bufferSize = strlen(firstNative) + strlen(secondNative) + 4;&lt;br&gt;
&amp;nbsp;&amp;nbsp; char* resultBuffer = new char[bufferSize];&lt;br&gt;
&amp;nbsp;&amp;nbsp; sprintf_s(resultBuffer, bufferSize, "%s + %s", firstNative, secondNative);&lt;br&gt;
&amp;nbsp;&amp;nbsp; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp; // marshal unmanaged character array to managed string&lt;br&gt;
&amp;nbsp;&amp;nbsp; String^ result = Marshal::PtrToStringAnsi(static_cast&amp;lt;IntPtr&amp;gt;(resultBuffer));&lt;br&gt;
&amp;nbsp;&amp;nbsp; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp; // free all unmanaged buffers&lt;br&gt;
&amp;nbsp;&amp;nbsp; delete[] resultBuffer;&lt;br&gt;
&amp;nbsp;&amp;nbsp; Marshal::FreeHGlobal(firstPtr);&lt;br&gt;
&amp;nbsp;&amp;nbsp; Marshal::FreeHGlobal(secondPtr);&lt;br&gt;
&amp;nbsp;&amp;nbsp; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp; // return managed string&lt;br&gt;
&amp;nbsp;&amp;nbsp; return result;&lt;br&gt;
}&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
It should be noted that it wouldn’t make any sense switching to unmanaged code to
do some string operations only as shown above. This is for demonstration purposes
only and you would usually call some unmanaged libraries or the like instead of it.
But it is a nice demonstration how cumbersome string operations were in C. If you
were doing this once, the &lt;font face="Courier New"&gt;sprintf_s&lt;/font&gt; function call
might have caught your attention. It’s a &lt;a href="http://msdn2.microsoft.com/en-us/library/ms235384.aspx"&gt;safe
implementation&lt;/a&gt; of &lt;font face="Courier New"&gt;sprintf&lt;/font&gt; which prevents buffer
overflows.
&lt;/p&gt;
&lt;p&gt;
Another point worth mentioning is that you have to take care of allocated memory for
the conversion since your character array is now allocated on the unmanaged heap.
Make sure you use the &lt;font face="Courier New"&gt;FreeHGlobal&lt;/font&gt; method to do it,
not the &lt;font face="Courier New"&gt;free&lt;/font&gt; (used for freeing memory allocated by &lt;font face="Courier New"&gt;*alloc&lt;/font&gt; calls
– ANSI C style) or &lt;font face="Courier New"&gt;delete&lt;/font&gt; (used for freeing memory
allocated by &lt;font face="Courier New"&gt;new&lt;/font&gt; calls – C++ style) functions.
&lt;/p&gt;
&lt;p&gt;
To reduce the code overhead of string conversions between managed and unmanaged world
you might consider wrapping it into a &lt;a href="http://blogs.msdn.com/jeremykuhne/archive/2005/06/11/428363.aspx"&gt;helper
class&lt;/a&gt;. This should also help preventing unwanted memory leaks during the conversions.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=330dfd2e-d438-41fb-ae74-1bafc8ca9076" /&gt;</description>
      <comments>http://www.damirscorner.com/CommentView,guid,330dfd2e-d438-41fb-ae74-1bafc8ca9076.aspx</comments>
      <category>Development</category>
      <category>Development/.NET</category>
      <category>Development/C++</category>
      <category>Development/Interop</category>
    </item>
    <item>
      <trackback:ping>http://www.damirscorner.com/Trackback.aspx?guid=8a180e88-04f6-4619-983d-055ccb83c536</trackback:ping>
      <pingback:server>http://www.damirscorner.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.damirscorner.com/PermaLink,guid,8a180e88-04f6-4619-983d-055ccb83c536.aspx</pingback:target>
      <dc:creator>Damir Arh</dc:creator>
      <wfw:comment>http://www.damirscorner.com/CommentView,guid,8a180e88-04f6-4619-983d-055ccb83c536.aspx</wfw:comment>
      <wfw:commentRss>http://www.damirscorner.com/SyndicationService.asmx/GetEntryCommentsRss?guid=8a180e88-04f6-4619-983d-055ccb83c536</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Less than a month ago I was certain I’d never have to write managed code in C++. With
such a set of mind I didn’t really care about the new features being added and improvements
being made to managed C++ since the first Visual Studio .NET. Luckily there were people
thinking otherwise and as a result this – often overlooked – member of the .NET family
got better with every release and is actually quite nice in the 2005 version. Don’t
get me wrong – it still is C++ and you probably wouldn’t want to use it if you could
get away with C# or VB. But if <a href="http://www.damirscorner.com/blog/CProjectBuildFromNetworkShareFailsInVS2005.aspx">platform
invoke</a> is giving you too many headaches you might want to take a look at it. It
could be the easiest way to solve your problem.
</p>
        <p>
To make this a little bit easier for those of you who haven’t used C++ for some time
and didn’t bother to check managed C++ at all, I’ll provide a small sample to help
out with the beginner’s problems I had when starting out.
</p>
        <p>
In a situation like mine you’ll usually want to write a class library to wrap the
unmanaged calls for undisturbed use within you managed project. In my case I’ll be
implementing an interface but writing a standalone class is not much different.
</p>
        <p>
Let’s start with the header file. You might remember that C++ requires the separation
of class declaration from method definition, the former being done in a header (<font face="Courier New">*.h</font>)
file and the latter in a code (<font face="Courier New">*.cpp</font>) file. I admit
being a little bit spoiled by not having to do that any more in C#. Let’s name our
header <font face="Courier New">MCPP.h</font> (fell free to guess what it stands for):
</p>
        <p>
          <font face="Courier New">using namespace System;</font>
        </p>
        <p>
          <font face="Courier New">namespace DamirsCorner 
<br />
{<br />
   namespace Samples<br />
   {<br />
      namespace LateBinding<br />
      {<br />
         public ref class MCPP : IBind<br />
         {<br />
         public:<br />
            virtual String^
Together(String^ first, String^ second);<br />
         };<br />
      }<br />
   }<br />
}</font>
        </p>
        <p>
It looks like a hybrid between C++ and C# and one could argue that’s what it actually
is. I’d like to point out the following:
</p>
        <ul>
          <li>
The <font face="Courier New">using</font> directive has an additional keyword <font face="Courier New">namespace</font>.
Also a double colon (static separator in C++) would be used to separate nested namespaces
instead of a dot. You’ll see this in the code file which follows. 
</li>
          <li>
To put your own code into a nested namespace, you’ll have to actually nest the <font face="Courier New">namespace</font> declarations.
Separating several of them with double colons won’t work. 
</li>
          <li>
To declare a managed class, use the additional keyword <font face="Courier New">ref</font>. 
</li>
          <li>
Don’t forget the different use of the <font face="Courier New">public</font> keyword
for the members in C++ compared to C#. 
</li>
          <li>
The <font face="Courier New">^</font> character denotes a reference to a managed object
(stored on the managed heap), separating it from unmanaged pointers (<font face="Courier New">*</font> character). 
</li>
          <li>
Notice the interface <font face="Courier New">IBind</font> being implemented by the
class. A standalone class wouldn’t need this of course. The <font face="Courier New">virtual</font> keyword
in the method declaration would also be skipped in this case.</li>
        </ul>
        <p>
This is it for the header file. Let’s look at the code file now:
</p>
        <p>
          <font face="Courier New">#include "MCPP.h"</font>
        </p>
        <p>
          <font face="Courier New">using namespace System;<br />
using namespace DamirsCorner::Samples::LateBinding;</font>
        </p>
        <p>
          <font face="Courier New">String^ MCPP::Together(String^ first, String^ second)<br />
{<br />
   return String::Empty;<br />
}</font>
        </p>
        <p>
It’s pretty obvious the method doesn’t really do anything but it’s the skeleton we’re
focusing on at the moment. You should turn your attention to the following:
</p>
        <ul>
          <li>
The code file must <font face="Courier New">include</font> the header file it implements
(i.e. defines its methods). To refresh your C++ knowledge: it’s a good habit to use
quotes for internal project header files and pointy brackets for external library
header files. The compiler looks in the project directory first for the former and
in the include directories first for the latter. It checks the other location if it
doesn’t find the file but it will work faster if you use the right one (not to mention
that by doing it you’re avoiding the problem of locating the wrong include with
the same name). 
</li>
          <li>
You can notice the double colons as namespace separators as I mentioned before. 
</li>
          <li>
The methods you’re implementing are not within the class declaration any more. You
already declared the class in the header file therefore you only set the method class
membership here by prefixing its name with the class name and a colon, just like you
were calling a static method.</li>
        </ul>
        <div>There’s a reason I used <font face="Courier New">String</font> for parameter
and return value type. While value types can be directly used in unmanaged code, reference
types have to be correctly marshaled. But that’s a complex enough topic to justify
a separate posting. The only thing left for this one is to make the code above compile.
Just start a new <font face="Courier New">Class Library project</font> in C++ (you’ll
find it in the <font face="Courier New">CLR</font> group) and paste the code to the
right files. After you reference the assembly containing the interface used (similar
to doing it in C#) the code should build successfully.
</div>
        <img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=8a180e88-04f6-4619-983d-055ccb83c536" />
      </body>
      <title>Implementing a managed interface in C++</title>
      <guid isPermaLink="false">http://www.damirscorner.com/PermaLink,guid,8a180e88-04f6-4619-983d-055ccb83c536.aspx</guid>
      <link>http://www.damirscorner.com/ImplementingAManagedInterfaceInC.aspx</link>
      <pubDate>Sun, 14 May 2006 17:11:27 GMT</pubDate>
      <description>&lt;p&gt;
Less than a month ago I was certain I’d never have to write managed code in C++. With
such a set of mind I didn’t really care about the new features being added and improvements
being made to managed C++ since the first Visual Studio .NET. Luckily there were people
thinking otherwise and as a result this – often overlooked – member of the .NET family
got better with every release and is actually quite nice in the 2005 version. Don’t
get me wrong – it still is C++ and you probably wouldn’t want to use it if you could
get away with C# or VB. But if &lt;a href="http://www.damirscorner.com/blog/CProjectBuildFromNetworkShareFailsInVS2005.aspx"&gt;platform
invoke&lt;/a&gt; is giving you too many headaches you might want to take a look at it. It
could be the easiest way to solve your problem.
&lt;/p&gt;
&lt;p&gt;
To make this a little bit easier for those of you who haven’t used C++ for some time
and didn’t bother to check managed C++ at all, I’ll provide a small sample to help
out with the beginner’s problems I had when starting out.
&lt;/p&gt;
&lt;p&gt;
In a situation like mine you’ll usually want to write a class library to wrap the
unmanaged calls for undisturbed use within you managed project. In my case I’ll be
implementing an interface but writing a standalone class is not much different.
&lt;/p&gt;
&lt;p&gt;
Let’s start with the header file. You might remember that C++ requires the separation
of class declaration from method definition, the former being done in a header (&lt;font face="Courier New"&gt;*.h&lt;/font&gt;)
file and the latter in a code (&lt;font face="Courier New"&gt;*.cpp&lt;/font&gt;) file. I admit
being a little bit spoiled by not having to do that any more in C#. Let’s name our
header &lt;font face="Courier New"&gt;MCPP.h&lt;/font&gt; (fell free to guess what it stands for):
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;using namespace System;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;namespace DamirsCorner 
&lt;br&gt;
{&lt;br&gt;
&amp;nbsp;&amp;nbsp; namespace Samples&lt;br&gt;
&amp;nbsp;&amp;nbsp; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; namespace LateBinding&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public ref class MCPP : IBind&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public:&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; virtual String^
Together(String^ first, String^ second);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
&amp;nbsp;&amp;nbsp; }&lt;br&gt;
}&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
It looks like a hybrid between C++ and C# and one could argue that’s what it actually
is. I’d like to point out the following:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The &lt;font face="Courier New"&gt;using&lt;/font&gt; directive has an additional keyword &lt;font face="Courier New"&gt;namespace&lt;/font&gt;.
Also a double colon (static separator in C++) would be used to separate nested namespaces
instead of a dot. You’ll see this in the code file which follows. 
&lt;/li&gt;
&lt;li&gt;
To put your own code into a nested namespace, you’ll have to actually nest the &lt;font face="Courier New"&gt;namespace&lt;/font&gt; declarations.
Separating several of them with double colons won’t work. 
&lt;/li&gt;
&lt;li&gt;
To declare a managed class, use the additional keyword &lt;font face="Courier New"&gt;ref&lt;/font&gt;. 
&lt;/li&gt;
&lt;li&gt;
Don’t forget the different use of the &lt;font face="Courier New"&gt;public&lt;/font&gt; keyword
for the members in C++ compared to C#. 
&lt;/li&gt;
&lt;li&gt;
The &lt;font face="Courier New"&gt;^&lt;/font&gt; character denotes a reference to a managed object
(stored on the managed heap), separating it from unmanaged pointers (&lt;font face="Courier New"&gt;*&lt;/font&gt; character). 
&lt;/li&gt;
&lt;li&gt;
Notice the interface &lt;font face="Courier New"&gt;IBind&lt;/font&gt; being implemented by the
class. A standalone class wouldn’t need this of course. The &lt;font face="Courier New"&gt;virtual&lt;/font&gt; keyword
in the method declaration would also be skipped in this case.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
This is it for the header file. Let’s look at the code file now:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;#include "MCPP.h"&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;using namespace System;&lt;br&gt;
using namespace DamirsCorner::Samples::LateBinding;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;String^ MCPP::Together(String^ first, String^ second)&lt;br&gt;
{&lt;br&gt;
&amp;nbsp;&amp;nbsp; return String::Empty;&lt;br&gt;
}&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
It’s pretty obvious the method doesn’t really do anything but it’s the skeleton we’re
focusing on at the moment. You should turn your attention to the following:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The code file must &lt;font face="Courier New"&gt;include&lt;/font&gt; the header file it implements
(i.e. defines its methods). To refresh your C++ knowledge: it’s a good habit to use
quotes for internal project header files and pointy brackets for external library
header files. The compiler looks in the project directory first for the former and
in the include directories first for the latter. It checks the other location if it
doesn’t find the file but it will work faster if you use the right one (not to mention
that by doing it&amp;nbsp;you’re avoiding the problem of locating the wrong include with
the same name). 
&lt;/li&gt;
&lt;li&gt;
You can notice the double colons as namespace separators as I mentioned before. 
&lt;/li&gt;
&lt;li&gt;
The methods you’re implementing are not within the class declaration any more. You
already declared the class in the header file therefore you only set the method class
membership here by prefixing its name with the class name and a colon, just like you
were calling a static method.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;There’s a reason I used &lt;font face="Courier New"&gt;String&lt;/font&gt; for parameter
and return value type. While value types can be directly used in unmanaged code, reference
types have to be correctly marshaled. But that’s a complex enough topic to justify
a separate posting. The only thing left for this one is to make the code above compile.
Just start a new &lt;font face="Courier New"&gt;Class Library project&lt;/font&gt; in C++ (you’ll
find it in the &lt;font face="Courier New"&gt;CLR&lt;/font&gt; group) and paste the code to the
right files. After you reference the assembly containing the interface used (similar
to doing it in C#) the code should build successfully.
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=8a180e88-04f6-4619-983d-055ccb83c536" /&gt;</description>
      <comments>http://www.damirscorner.com/CommentView,guid,8a180e88-04f6-4619-983d-055ccb83c536.aspx</comments>
      <category>Development</category>
      <category>Development/.NET</category>
      <category>Development/C++</category>
      <category>Development/Interop</category>
    </item>
    <item>
      <trackback:ping>http://www.damirscorner.com/Trackback.aspx?guid=fc3995de-ce4c-4410-8fd7-08090a7084b5</trackback:ping>
      <pingback:server>http://www.damirscorner.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.damirscorner.com/PermaLink,guid,fc3995de-ce4c-4410-8fd7-08090a7084b5.aspx</pingback:target>
      <dc:creator>Damir Arh</dc:creator>
      <wfw:comment>http://www.damirscorner.com/CommentView,guid,fc3995de-ce4c-4410-8fd7-08090a7084b5.aspx</wfw:comment>
      <wfw:commentRss>http://www.damirscorner.com/SyndicationService.asmx/GetEntryCommentsRss?guid=fc3995de-ce4c-4410-8fd7-08090a7084b5</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Completely unexpectedly I stumbled across Platform Invocation Services today when
I was introduced to the <a href="http://publib.boulder.ibm.com/tividd/td/TSMC/GC32-0793-02/en_US/HTML/ansa000002.htm">IBM
Tivoli Storage Manager API</a>. It should have been a simple case of getting to know
the API and writing a sample application with it, but it turned out that there’s no
managed wrapper available for it (in spite of first being told otherwise). Combine
that fact with an abundance of low level calls and large structs as their parameters
and you can imagine that after one day there’s still a long way to that sample application,
not to mention the final solution.
</p>
        <p>
For anybody else like me out there who hasn’t done more than an occasional <font face="Courier New">DllImport</font> call
or two the following resources should help getting to grips with the PInvoke basics:
</p>
        <ul>
          <li>
            <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkPlatformInvokeTutorial.asp">Platform
Invoke Tutorial</a> – a must read for anyone starting with PInvoke. As usual, the
follow-up links provide lots of additional useful information.</li>
          <li>
            <a href="http://pinvoke.net/index.aspx">PINVOKE.NET</a> – an indispensable source
of information on WinAPI PInvoke calls. Not exactly what I needed but still the abundance
of example calls turned out helpful.</li>
          <li>
            <a href="http://www.paulyao.com/resources/tools/pinvoke.asp">The P/Invoke Wizard</a> – a simple
tool for converting C/C++ include files to PInvoke declarations. Not perfect and a
bit pricy for what it does but still worth it due to the time it can save you when
dealing with many large include files.</li>
        </ul>
        <div>I hope you find these useful just as I did.
</div>
        <img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=fc3995de-ce4c-4410-8fd7-08090a7084b5" />
      </body>
      <title>Useful PInvoke resources</title>
      <guid isPermaLink="false">http://www.damirscorner.com/PermaLink,guid,fc3995de-ce4c-4410-8fd7-08090a7084b5.aspx</guid>
      <link>http://www.damirscorner.com/UsefulPInvokeResources.aspx</link>
      <pubDate>Wed, 03 May 2006 21:34:25 GMT</pubDate>
      <description>&lt;p&gt;
Completely unexpectedly I stumbled across Platform Invocation Services today when
I was introduced to the &lt;a href="http://publib.boulder.ibm.com/tividd/td/TSMC/GC32-0793-02/en_US/HTML/ansa000002.htm"&gt;IBM
Tivoli Storage Manager API&lt;/a&gt;. It should have been a simple case of getting to know
the API and writing a sample application with it, but it turned out that there’s no
managed wrapper available for it (in spite of first being told otherwise). Combine
that fact with an abundance of low level calls and large structs as their parameters
and you can imagine that after one day there’s still a long way to that sample application,
not to mention the final solution.
&lt;/p&gt;
&lt;p&gt;
For anybody else like me out there who hasn’t done more than an occasional &lt;font face="Courier New"&gt;DllImport&lt;/font&gt; call
or two the following resources should help getting to grips with the PInvoke basics:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkPlatformInvokeTutorial.asp"&gt;Platform
Invoke Tutorial&lt;/a&gt; – a must read for anyone starting with PInvoke. As usual, the
follow-up links provide lots of additional useful information.&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://pinvoke.net/index.aspx"&gt;PINVOKE.NET&lt;/a&gt; – an indispensable source
of information on WinAPI PInvoke calls. Not exactly what I needed but still the abundance
of example calls turned out helpful.&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://www.paulyao.com/resources/tools/pinvoke.asp"&gt;The P/Invoke Wizard&lt;/a&gt; –&amp;nbsp;a&amp;nbsp;simple
tool for converting C/C++ include files to PInvoke declarations. Not perfect and a
bit pricy for what it does but still worth it due to the time it can save you when
dealing with many large include files.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;I hope you find these useful just as I did.
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.damirscorner.com/aggbug.ashx?id=fc3995de-ce4c-4410-8fd7-08090a7084b5" /&gt;</description>
      <comments>http://www.damirscorner.com/CommentView,guid,fc3995de-ce4c-4410-8fd7-08090a7084b5.aspx</comments>
      <category>Development</category>
      <category>Development/.NET</category>
      <category>Development/Interop</category>
    </item>
  </channel>
</rss>