<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Moy Blog &#187; windows</title>
	<atom:link href="http://www.moythreads.com/wordpress/category/windows/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.moythreads.com/wordpress</link>
	<description>Abandon All Hope, Ye Who Read This Blog</description>
	<lastBuildDate>Sun, 01 Jan 2012 19:20:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>IJW (It Just Works) and COM Interop</title>
		<link>http://www.moythreads.com/wordpress/2008/03/26/ijw-it-just-works-and-com-interop/</link>
		<comments>http://www.moythreads.com/wordpress/2008/03/26/ijw-it-just-works-and-com-interop/#comments</comments>
		<pubDate>Wed, 26 Mar 2008 05:05:24 +0000</pubDate>
		<dc:creator>moy</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.moythreads.com/wordpress/2008/03/26/ijw-it-just-works-and-com-interop/</guid>
		<description><![CDATA[As I promised in my last post, today I am going to give an overview about how to call C# code from C++. After googling around a bit you will find there are at least 2 well-known ways to call C# from C++. It Just Works The first one I want to mention is &#8220;IJW&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p>As I promised in my last post, today I am going to give an overview about how to call C# code from C++. After googling around a bit you will find there are at least 2 well-known ways to call C# from C++. </p>
<p><strong>It Just Works</strong></p>
<p>The first one I want to mention is &#8220;IJW&#8221; that stands for &#8220;It Just Works&#8221;. As the name implies, there is nothing much to discuss about IJW, is pretty easy to use, all one have to do is specify the /clr switch in the Microsoft VS compiler. This switch will cause your C++ code to be compiled to IL (Intermediate Language) and therefore will run in a managed environment. Nice isn&#8217;t it? However there is a catch, even though your code will be compiled to IL, the classes are not managed, which means among other things that the CLR will not take care of the memory. This is kind of obvious, since the original code was meant to take care of the memory itself, all the /clr switch does is give the opportunity to that old C++ code to run in managed environment.</p>
<p>Once that we have this C++ code working on a managed environment, there is some new fun stuff we can do with it.</p>
<style type="text/css">
.comment { color: #999999; font-style: italic; }
.pre { color: #000099; }
.string { color: #009900; }
.char { color: #009900; }
.float { color: #996600; }
.int { color: #999900; }
.bool { color: #000000; font-weight: bold; }
.type { color: #FF6633; }
.flow { color: #FF0000; }
.keyword { color: #990000; }
.operator { color: #663300; font-weight: bold; }
</style>
<p></head><br />
<body></p>
<pre><span class="pre">#using &lt;mscorlib.dll&gt;
#using &lt;myassembly.dll&gt;

#include &lt;stdio.h&gt;
</span><span class="keyword">
using namespace</span> System<span class="operator">;</span><span class="keyword">
using namespace</span> MyNameSpace<span class="operator">;</span><span class="type">

void</span> callSomethingInMyAssembly<span class="operator">()
{</span>

    Console<span class="operator">::</span>WriteLine<span class="operator">(</span><span class="string">"In Managed Environment!"</span><span class="operator">);</span>
    MyAssemblyClass<span class="operator">::</span>MyStaticMethod<span class="operator">();
}</span><span class="pre">

#pragma unmanaged
</span><span class="type">

void</span> oldAndCrappyFunction<span class="operator">()
{</span>
    callSomethingInMyAssembly<span class="operator">();
}</span></pre>
<p> The compiler pragma directive &#8220;managed&#8221; and &#8220;unmanaged&#8221; will help you to switch from managed to unmanaged and viceversa. This way you can call managed code from your old unmanaged code. Be aware that this solution will not work when you have an old DLL that other components depend on, since the resulting DLL will be a DLL with IL code and therefore not callable from other unmanaged DLLs.</p>
<p><strong>COM Interop</strong></p>
<p>To use COM Interop, the managed code, in this case, a C# class needs to allocate an <a href="http://en.wikipedia.org/wiki/UUID" target="_blank">UUID</a> to be used when creating a COM instance. The following code shows how to create code with an interface and class with UUIDs.</p>
<pre><span class="keyword">using</span> System<span class="operator">;</span><span class="keyword">

using</span> System<span class="operator">.</span>Runtime<span class="operator">.</span>InteropServices<span class="operator">;</span><span class="keyword">

namespace</span> ManagedNameSpace<span class="operator">
{</span><span class="comment">

/* The GUID should be generated using guidgen.exe */</span><span class="operator">
[</span>Guid<span class="operator">(</span><span class="string">"EF870CF7-DA0F-4bf7-89DD-DE21E4701E21"</span><span class="operator">)]</span><span class="keyword">
public</span> interface IManagedComponent<span class="operator">
{</span><span class="type">
        void</span> ManagedMethod<span class="operator">();
}

[</span>Guid<span class="operator">(</span><span class="string">"687EADD7-0B02-457a-85E5-84BEF198F7BA"</span><span class="operator">)]</span><span class="keyword">

public class</span> ManagedClass<span class="operator"> :</span> IManagedComponent<span class="operator">
{</span><span class="keyword">
        public</span><span class="type"> void</span> ManagedMethod<span class="operator">()
        {</span>

                Console<span class="operator">.</span>WriteLine<span class="operator">(</span><span class="string">"in managed environment!\n"</span><span class="operator">);
        }
}

}</span>
</pre>
<p>You can create a UUID using the tool guidgen.exe. The class should be compiled with</p>
<p> C:\csc /target:library mycomponent.cs </p>
<p>That will generate a mycomponent.dll assembly. In order to other COM components to use our C# class we must register the DLL, we can do so using regasm utility:</p>
<p>C:\regasm mycomponent.dll /tlb:mycomponent.tlb</p>
<p>Now that the DLL is registered you can use it from any language that supports COM, C++ included. Before proceeding to call this C# code from C++, you may be wondering about that mycomponent.tlb file specified as argument to regasm /tlb switch. That file is known as a &#8220;type library&#8221; and is used by the COM infrastructure to save meta-data about the types involved in the exported interfaces, that way any language that supports COM can interact with any other COM component, in this case, written in C#.</p>
<p>Finally let&#8217;s call our C# component from C++ code.</p>
<pre><span class="pre">#include &lt;windows.h&gt;
#include &lt;iostream&gt;

</span><span class="keyword">
using namespace</span> std<span class="operator">;</span><span class="pre">

#import &lt;mscorlib.tlb&gt; raw_interfaces_only

#import "dtcom.tlb" no_namespace named_guids
</span><span class="type">
int</span><span class="keyword"> main</span><span class="operator">(</span><span class="type">int</span> argc<span class="operator">,</span><span class="type"> char</span><span class="operator"> *</span>argv<span class="operator">[])
{</span>

        IManagedComponent<span class="operator"> *</span>component<span class="operator">;</span>
        HRESULT hr<span class="operator">;</span><span class="comment">

        /* COM require an initialize routine */</span>
        CoInitialize<span class="operator">(</span>NULL<span class="operator">);</span>

        hr<span class="operator"> =</span> CoCreateInstance<span class="operator">(</span>CLSID_ManagedClass<span class="operator">,</span> NULL<span class="operator">,</span>
                        CLSCTX_INPROC_SERVER<span class="operator">,</span> IID_IManagedComponent<span class="operator">,</span><span class="keyword"> reinterpret_cast</span><span class="operator">&lt;</span><span class="type">void</span><span class="operator"> **&gt;(&amp;</span>component<span class="operator">));</span><span class="flow">

        if</span><span class="operator"> (</span> FAILED<span class="operator">(</span>hr<span class="operator">) ) {</span>
                cerr<span class="operator"> &lt;&lt;</span><span class="string"> "Could not create component instance."</span><span class="operator"> &lt;&lt;</span> endl<span class="operator">;</span><span class="flow">

                return</span><span class="operator"> -</span><span class="int">1</span><span class="operator">;
        }</span> 

        cout<span class="operator"> &lt;&lt;</span><span class="string"> "Calling managed methods."</span><span class="operator"> &lt;&lt;</span> endl<span class="operator">;</span>
        component<span class="operator">-&gt;</span>ManagedMethod<span class="operator">();</span><span class="comment">

        /* COM Require to release the instance */</span>
        component<span class="operator">-&gt;</span>Release<span class="operator">();</span><span class="comment">

        /* Close COM */</span>
        CoUninitialize<span class="operator">();</span><span class="flow">

        return</span><span class="int"> 0</span><span class="operator">;
}</span>
</pre>
<p>As you can see we use the CoCreateInstance COM function to create an object that references (indirectly via <a href="http://msdn2.microsoft.com/en-us/library/f07c8z1c.aspx" target="_blank">CCW</a> ) to the C# object. </p>
<p>So, that&#8217;s it, you can <a href="http://en.wikipedia.org/wiki/Component_Object_Model" target="_blank">learn more about COM at Wikipedia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moythreads.com/wordpress/2008/03/26/ijw-it-just-works-and-com-interop/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PInvoke ( How to Call C from C# )</title>
		<link>http://www.moythreads.com/wordpress/2008/02/04/pinvoke-how-to-call-c-from-c/</link>
		<comments>http://www.moythreads.com/wordpress/2008/02/04/pinvoke-how-to-call-c-from-c/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 01:26:07 +0000</pubDate>
		<dc:creator>moy</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.moythreads.com/wordpress/2008/02/04/pinvoke-how-to-call-c-from-c/</guid>
		<description><![CDATA[I will be coding some C# stuff for Windows this year. We have a bunch of C/C++ APIs which we want to make available to our customers from C#, however, since I have known of the Mono existence for a while, I quickly realized that 90% the C# interfaces I will code on Windows for [...]]]></description>
			<content:encoded><![CDATA[<p>I will be coding some C# stuff for Windows this year. We have a bunch of C/C++ APIs  which we want to make available to our customers from C#, however, since I have known of the <a href="http://www.mono-project.com/" target="_blank">Mono</a> existence for a while, I quickly realized that 90% the C# interfaces I will code on Windows for our C/C++ APIs can be made available for our Linux product as well. This post will briefly show how to call C/C++ code from C#.</p>
<p>As most of the readers probably know, C# is one of the primary languages of the .NET platform, thus, runs in a managed environment and cannot call unmanaged code w/o some intermediate mechanism, but don&#8217;t fear, it is quite easy, that mechanism is PInvoke, that stands for Platform Invoke. Let&#8217;s see an example of how it is done, on Linux.</p>
<p>1. Create a C file, libtest.c with this content:</p>
<style type="text/css">
.comment { color: #999999; font-style: italic; }
.pre { color: #000099; }
.string { color: #009900; }
.char { color: #009900; }
.float { color: #996600; }
.int { color: #999900; }
.bool { color: #000000; font-weight: bold; }
.type { color: #FF6633; }
.flow { color: #FF0000; }
.keyword { color: #990000; }
.operator { color: #663300; font-weight: bold; }
</style>
<p></head><br />
<body></p>
<pre><span class="pre">#include &lt;stdio.h&gt;
</span><span class="type">
void</span> print<span class="operator">(</span><span class="keyword">const</span><span class="type"> char</span><span class="operator"> *</span>message<span class="operator">)
{</span>

        printf<span class="operator">(</span><span class="string">"%s\\n"</span><span class="operator">,</span> message<span class="operator">);
}</span>
</pre>
<p>That&#8217;s a simple pseudo-wrapper for printf. But represents any C function in the library you want to call. If you have a C++ function don&#8217;t forget to put extern &#8220;C&#8221; to avoid mangling the name.</p>
<p>2. Compile it as a shared library: gcc -fPIC -shared libtest.c -o libtest.so</p>
<p>3. Let&#8217;s create the C# file that will call our C API. It&#8217;s quite easy using PInvoke, all we need is define our entry points.</p>
<pre><span class="keyword">using</span> System<span class="operator">;</span><span class="keyword">

using</span> System<span class="operator">.</span>Runtime<span class="operator">.</span>InteropServices<span class="operator">;</span><span class="keyword">

public class</span> Tester<span class="operator">
{
        [</span>DllImport<span class="operator">(</span><span class="string">"libtest.so"</span><span class="operator">,</span> EntryPoint<span class="operator">=</span><span class="string">"print"</span><span class="operator"><span class="operator">)]</span><span class="keyword">

        static extern</span><span class="type"> void</span> print<span class="operator">(</span>string message<span class="operator">);</span><span class="keyword">

        public static</span><span class="type"> void</span> Main<span class="operator">(</span>string<span class="operator">[]</span> args<span class="operator">)
        {</span>

                print<span class="operator">(</span><span class="string">"Hello World C# =&gt; C++"</span><span class="operator">);
        }
}</span>
</pre>
<p>We define a test class that declares a method &#8220;print&#8221;. However we do not write the body of the method since we declare it extern and static because it will not depend on the class instance data. Using C# attribute DllImport we specify the DLL ( in Linux, the shared object ) where the method will be defined.</p>
<p>4. Compile the C# file: mcs test.cs</p>
<p>5. Run it: mono test.exe</p>
<p>Unless you have the library libtest.so in a standard library path like &#8220;/usr/lib&#8221;, you are likely to see a System.DllNotFoundException, to fix this you can move your libtest.so to /usr/lib, or better yet, just add your CWD to the library path: export LD_LIBRARY_PATH=`pwd`</p>
<p>6. Run it again <img src='http://www.moythreads.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  &#8230; now you should see the hello world C# => C++ message.</p>
<p>The DllImport attribute supports other arguments to tweak its behavior, refer to MSDN for DllImport documentation. Also keep in mind this is a extremely simple example, when more complex data types are involved we need to read about <a href="http://www.arstdesign.com/articles/interopmarshaling.html" target="_blank">marshaling</a>.</p>
<p>So that&#8217;s it, in my next post I will write about how to call C# code from C/C++ using COM Interop and managed C++.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moythreads.com/wordpress/2008/02/04/pinvoke-how-to-call-c-from-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

