<?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>Marius Bancila's Blog &#187; Tutorials</title>
	<atom:link href="http://mariusbancila.ro/blog/category/articles_and_tutorials/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://mariusbancila.ro/blog</link>
	<description>Sharing my opinions and ideas!</description>
	<lastBuildDate>Mon, 14 Nov 2011 07:19:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>32-bit and 64-bit COM Servers</title>
		<link>http://mariusbancila.ro/blog/2010/11/04/32-bit-and-64-bit-com-servers/</link>
		<comments>http://mariusbancila.ro/blog/2010/11/04/32-bit-and-64-bit-com-servers/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 13:59:23 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[64bit]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[registry]]></category>
		<category><![CDATA[x64]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=775</guid>
		<description><![CDATA[It is possible to register both 32-bit and 64-bit versions of the same COM server on 64-bit machine. This leads to several questions such as how are they registered and which one of the two is used. I will try to answer them below. But first, let&#8217;s start with an example. Example Let&#8217;s say we [...]]]></description>
			<content:encoded><![CDATA[<p>It is possible to register both 32-bit and 64-bit versions of the same COM server on 64-bit machine. This leads to several questions such as how are they registered and which one of the two is used. I will try to answer them below. But first, let&#8217;s start with an example.</p>
<p><strong>Example</strong><br />
Let&#8217;s say we have the a simple COM local server called COM3264Server.exe. There is just one interface called ICoCOM3264Server. Here is the IDL file:</p>
<pre name="code" class="cpp">
[
	object,
	uuid(733C70A7-F7EC-4C15-85D2-5CDB14F4110B),
	dual,
	nonextensible,
	pointer_default(unique)
]
interface ICoCOM3264Server : IDispatch{
   [id(1), helpstring("Says hello")] HRESULT SayHello(void);
};
[
	uuid(2F25FC66-2380-42FD-8476-8B5917FB1BF1),
	version(1.0),
]
library COM3264ServerLib
{
	importlib("stdole2.tlb");
	[
		uuid(9268A299-E817-4C5D-8627-C2582B66F16D)
	]
	coclass CoCOM3264Server
	{
		[default] interface ICoCOM3264Server;
	};
};
</pre>
<p>The implementation of the method SayHello() is straight forward; it just displays a message box with a text that varies between the two architectures, x64 and x86.</p>
<pre name="code" class="cpp">
STDMETHODIMP CCoCOM3264Server::SayHello(void)
{
#ifdef _WIN64
   ::MessageBox(NULL, _T("Hello from 64-bit COM server!"), _T("COM3264Server"), MB_OK);
#else
   ::MessageBox(NULL, _T("Hello from 32-bit COM server!"), _T("COM3264Server"), MB_OK);
#endif

   return S_OK;
}
</pre>
<p><strong>Registry</strong><br />
When you register the COM server, the 32-bit and 64-bit versions are registered in different parts of the registry. On 64-bit machine, the registry has two views (or modes):</p>
<ul>
<li>a native view, for 64-bit application; (e.g. registry path for CLSIDs is HKEY_CLASSES_ROOT\CLSID\)</li>
<li>a WOW64 view, which enables redirections for 32-bit applications, a process transparent to the user (e.g. registry path for CLSIDs is HKEY_CLASSES_ROOT\Wow6432Node\CLSID\)</li>
</ul>
<p>Here is the Registry registration of the (native) 64-bit COM server (notice the registry key in the status bar of the editor, and the path to the server executable).<br />
<img alt="" src="/blog/wp-content/uploads/2010/11/com3264server_reg64.png" title="Native registry view" class="alignnone" width="891" height="319" /></p>
<p>On, the other hand, the 32-bit COM server is registered under the Wow6432 node.<br />
<img alt="" src="/blog/wp-content/uploads/2010/11/com3264server_reg32.png" title="Wow64 registry view" class="alignnone" width="891" height="319" /></p>
<p>So if both versions are registered in Windows Registry, which one is picked? Well, both the server and the client can specify which architecture to use:</p>
<ul>
<li>the COM server can do this via the <strong>PreferredServerBitness</strong> Registry value</li>
<li>the client can do this using one of the flags <strong>CLSCTX_ACTIVATE_32_BIT_SERVER</strong> and <strong>CLSCTX_ACTIVATE_64_BIT_SERVER</strong>, which overrides the server preference</li>
</ul>
<p>If neither the client nor the server specifies a preference, then:</p>
<ul>
<li>If the computer that hosts the server is running Windows Server 2003 with Service Pack 1 (SP1) or a later system, then COM will try to match the server architecture to the client architecture. In other words, for a 32-bit client, COM will activate a 32-bit server if available; otherwise it will activate a 64-bit version of the server. For a 64-bit client, COM will activate a 64-bit server if available; otherwise it will activate a 32-bit server.</li>
<li>If the computer that hosts the server is running Windows XP or Windows Server 2003 without SP1 or later installed, then COM will prefer a 64-bit version of the server if available; otherwise it will activate a 32-bit version of the server.</li>
</ul>
<p><strong>Server Preference</strong><br />
The server can specify its preferred architecture in the <a href="http://msdn.microsoft.com/en-us/library/ms694319%28v=VS.85%29.aspx">PreferredServerBitness</a> value under AppId (available only on 64-bit Windows). This integer value can be:</p>
<ul>
<li><strong>1</strong>: Match the server architecture to the client architecture. For example, if the client is 32-bit, use a 32-bit version of the server, if it is available. If not, the client&#8217;s activation request will fail.</li>
<li><strong>2</strong>: Use a 32-bit version of the server. If one does not exist, the client&#8217;s activation request will fail.</li>
<li><strong>3</strong>: Use a 64-bit version of the server. If one does not exist, the client&#8217;s activation request will fail.</li>
</ul>
<p>Here is the value set in Registry to specify the 64-bit architecture.<br />
<img alt="" src="/blog/wp-content/uploads/2010/11/com3264server_regappid.png" title="Registry AppId" class="alignnone" width="891" height="319" /></p>
<p>When you run the client, it launches the 64-bit version and in my example the following window pops-up:<br />
<img alt="" src="/blog/wp-content/uploads/2010/11/com3264server_64bit.png" title="64-bit COM message" class="alignnone" width="214" height="144" /></p>
<p>If I change the value to indicate the 32-bit architecture, the other COM server is launched and the displayed message is:<br />
<img alt="" src="/blog/wp-content/uploads/2010/11/com3264server_32bit.png" title="32-bit COM message" class="alignnone" width="214" height="144" /></p>
<p><strong>Client Preference</strong><br />
The client code I used so far looked like this:</p>
<pre name="code" class="cpp">
   ICoCOM3264Server* pServer;

   HRESULT hr = ::CoCreateInstance(
      CLSID_CoCOM3264Server,
      NULL,
      CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER,
      IID_ICoCOM3264Server,
      (void**)&#038;pServer);

   if(SUCCEEDED(hr))
   {
      pServer->SayHello();

      pServer->Release();
   }
</pre>
<p>However, the 64-bit version of Windows added new flags to the <a href="http://msdn.microsoft.com/en-us/library/ms693716%28v=VS.85%29.aspx">CLSCTX</a> enumeration.</p>
<ul>
<li><strong>CLSCTX_ACTIVATE_32_BIT_SERVER</strong>: used to activate or connect to a 32-bit version of the server; fail if one is not registered.</li>
<li><strong>CLSCTX_ACTIVATE_64_BIT_SERVER</strong>: used to activate or connect to a 64 bit version of the server; fail if one is not registered.</li>
</ul>
<p>As I mentioned earlier, if the client uses one of these flags, it overrides the server preference (specified via the PreferredServerBitness Registry value). </p>
<p>In the following example, the client requests the 64-bit COM server:</p>
<pre name="code" class="cpp">
   HRESULT hr = ::CoCreateInstance(
      CLSID_CoCOM3264Server,
      NULL,
      CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER|CLSCTX_ACTIVATE_64_BIT_SERVER,
      IID_ICoCOM3264Server,
      (void**)&#038;pServer);
</pre>
<p>And if you run it, no matter what the server specified, the 64-bit COM server is launched.</p>
<p>To read more about the subject see the MSDN links above.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/11/04/32-bit-and-64-bit-com-servers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>COM Apartments</title>
		<link>http://mariusbancila.ro/blog/2010/06/28/com-apartments/</link>
		<comments>http://mariusbancila.ro/blog/2010/06/28/com-apartments/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 16:39:51 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[COM]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[apartments]]></category>
		<category><![CDATA[ATL]]></category>
		<category><![CDATA[MTA]]></category>
		<category><![CDATA[NTA]]></category>
		<category><![CDATA[STA]]></category>
		<category><![CDATA[thread-safe]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=571</guid>
		<description><![CDATA[If you work with COM, apartments is one of the concepts you must comprehend, because it&#8217;s an important topic. Before explaining what apartments are let&#8217;s think about classes and objects regardless of COM. When you build a class, you know (or you should) whether objects of that class will be used from a single thread, [...]]]></description>
			<content:encoded><![CDATA[<p>If you work with COM, apartments is one of the concepts you must comprehend, because it&#8217;s an important topic. Before explaining what apartments are let&#8217;s think about classes and objects regardless of COM. When you build a class, you know (or you should) whether objects of that class will be used from a single thread, or from multiple threads. In the later case, if those threads might access shared data at the same time, you must synchronize the access to that data (using critical sections, mutexes, or others). So when you create your class you either make it thread-safe or not. If it&#8217;s not thread safe, objects of that class can only be accessed from one thread at a time, if it&#8217;s thread-safe, then objects of that class can be accessed from different threads at the same time.</p>
<p>Now, the same rule applies in the COM world. Your coclasses can either be thread-safe or not. If the are thread-safe, you can access one object from different threads at a time, otherwise not. Here enter the apartments. So what is an apartment? An apartment is an environment in which COM objects can live. It&#8217;s not a thread, nor a process, but it handles access from COM clients to COM objects. There are several types of apartments: single-threaded apartments (STA), multi-threaded apartments (MTA) and neutral-threaded apartments (NTA).</p>
<p><strong>Single-Threaded Apartments</strong><br />
An STA allows only one thread at a time to access a COM object. This is  achieved using a hidden window with a message pump. Calls from clients living in different threads are queued with the message pump. Only when the current call from a thread ends, the next call can proceed.</p>
<p>Assume you had a COM object called CoUserGroups that implements an interface IUserGroups that provides two methods: one called Add that adds a new user group, and one called Delete that deletes a user group. Since both methods work on the same list of user groups, adding and deleting is not possible at the same time without synchronizing access. But since such synchronization was not implemented, the COM object specifies that it can leave only in an STA, and let the apartment do the synchronization of calls from clients living in different threads.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/06/com_sta.png" title="COM STA" class="alignnone" width="688" height="326" /></p>
<p><strong>Multi-Threaded Apartments</strong><br />
An MTA allows any number of threads to access a COM objects. However, the COM objects must be thread-safe, otherwise your application will behave unexpectedly and even crash.</p>
<p>Going back to the previous example, if CoUserGroups was implemented in a thread-safe manner, then it would be possible for clients living in different threads to access it. In this case there would be no need for an apartment level synchronization. The COM coclass specifies that it can live in an MTA and when simultaneous calls from different threads are received they are directed immediately to the COM object. This situation is shown in the next image.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/06/com_mta.png" title="COM MTA" class="alignnone" width="688" height="327" /></p>
<p><strong>Neutral-Threaded Apartments</strong><br />
NTAs, like MTAs, allow multiple threads to enter one apartment, but once a thread entered the apartment it acquires an apartment wide lock that will block the other threads, until the current thread exists the apartment. Calls into NTA (from STA or MTA in the same process) do not generate context switches; the thread leaves the apartment in which it executes and enters the NTA without any context switch, which increases performance. This model was introduced with COM+ (in Windows 2000) and is meant for components with no user interface. </p>
<p>A process can contain several apartments:</p>
<ul>
<li>zero or one MTA</li>
<li>zero or one NTA</li>
<li>zero, one or several STAs; the first STA created for a process is called the main STA</li>
</ul>
<p>As a COM client, you specify the apartment you want to join with a call to CoInitializeEx(). This methods must be called from each thread.</p>
<pre name="code" class="cpp">
HRESULT CoInitializeEx(void * pvReserved, DWORD dwCoInit);
</pre>
<p>The second parameters is a set of flags specifying the initialization options for the thread. To join the unique MTA, use COINIT_MULTITHREADED. To join a new or existing STA, use COINIT_APARTMENTTHREADED. Function CoInitialize() calls CoInitializeEx() specifying COINIT_APARTMENTTHREADED for the flags. </p>
<p><strong>How to specify the threading model allowed for a coclass?</strong><br />
A coclass can specify the type of apartment it can join. If you&#8217;re using ATL you can specify that when you create the coclass. The next image shows the available options:</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/06/com_atlapartment.png" title="ATL apartment choices" class="alignnone" width="615" height="520" /><br />
What they mean:</p>
<ul>
<li><strong>Single</strong>: object wants to join the main STA (the first STA created into the process)</li>
<li><strong>Apartment</strong>: object wants to join one of the STAs in the process</li>
<li><strong>Both</strong>: object wants to join either an STA or the MTA</li>
<li><strong>Free</strong>: object wants to join the MTA</li>
<li><strong>Neutral</strong>: object wants to join the NTA</li>
</ul>
<p>ATL adds the appropriate value to the registry script it creates for your coclass. COM depends entirely on the registry, and the threading model is also specified in the registry. Here is an example:</p>
<pre name="code" class="cpp">
HKCR
{
	NoRemove CLSID
	{
		ForceRemove {80CFA233-86CC-44E3-9A62-BC498D8F2A0E} = s 'CoUserGroups Class'
		{
			ForceRemove Programmable
			InprocServer32 = s '%MODULE%'
			{
				val ThreadingModel = s 'Apartment'
			}
			TypeLib = s '{B8965B61-2A5A-4F34-B9F8-D8859452D345}'
			Version = s '1.0'
		}
	}
}
</pre>
<p>When that is merged into the Windows Registry, it looks like this:<br />
<img alt="" src="/blog/wp-content/uploads/2010/06/com_regthreadmodel.png" title="Threading model in Registry" class="alignnone" width="793" height="370" /></p>
<p>The possible values in registry are:</p>
<ul>
<li>no value specified: equivalent of ATL &#8216;Single&#8217;</li>
<li><strong>Apartment</strong>: equivalent of ATL &#8216;Apartment&#8217;</li>
<li><strong>Free</strong>: equivalent of ATL &#8216;Free&#8217;</li>
<li><strong>Both</strong>: equivalent of ATL &#8216;Both&#8217;</li>
<li><strong>Neutral</strong>: equivalent of ATL &#8216;Neutral&#8217;</li>
</ul>
<p>If you want to read more about COM apartments I suggests articles like this <a href="http://www.codeguru.com/cpp/com-tech/activex/apts/article.php/c5529">one</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/06/28/com-apartments/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>.NET out string[] to Automation SAFEARRAY**</title>
		<link>http://mariusbancila.ro/blog/2009/07/23/net-out-string-to-automation-safearray/</link>
		<comments>http://mariusbancila.ro/blog/2009/07/23/net-out-string-to-automation-safearray/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 11:44:13 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[MFC]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Windows Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[SAFEARRAY]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=328</guid>
		<description><![CDATA[.NET allows you to expose components as COM and consume them from unmanaged code. There are many references on how to this (and you can only start with MSDN), and I will not talk about that part. What I want to explain here is something different. Suppose you have this interface: [Guid("2F8433FE-4771-4037-B6B2-ED5F6585ED04")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface [...]]]></description>
			<content:encoded><![CDATA[<p>.NET allows you to expose components as COM and consume them from unmanaged code. There are many references on how to this (and you can only start with <a href="http://msdn.microsoft.com/en-us/library/zsfww439(VS.71).aspx" target="_blank">MSDN</a>), and I will not talk about that part. What I want to explain here is something different. Suppose you have this interface:</p>
<pre name="code" class="csharp">
[Guid("2F8433FE-4771-4037-B6B2-ED5F6585ED04")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IAccounts
{
      [DispId(1)]
      string[] GetUsers();
}
</pre>
<p>Method GetUsers() returns an array on string representing the user names. But what if you also wanted the user passwords or addresses? Since this is exposed as COM, you cannot return an array of User. But you can return multiple arrays of string. So, how would you deal with out string[]? This is what I want to show you in this tutorial.</p>
<p>This is a .NET interface exposed to COM. It has two methods, GetUsers() that returns an array of string representing user names, and GetUsers2() that returns an array of strings as an output parameters and a bool as return type, indicating whether any user was found.</p>
<pre name="code" class="csharp">
namespace SampleLibrary
{
   [Guid("2F8433FE-4771-4037-B6B2-ED5F6585ED04")]
   [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
   public interface IAccounts
   {
      [DispId(1)]
      string[] GetUsers();

      [DispId(2)]
      bool GetUsers2(out string [] users);
   }
}
</pre>
<p>And this is the implementation:</p>
<pre name="code" class="csharp">
namespace SampleLibrary
{
   [Guid("C4713144-5D29-4c65-BF9C-188B1B7CD2B6")]
   [ClassInterface(ClassInterfaceType.None)]
   [ProgId("SampleLibrary.DataQuery")]
   public class Accounts : IAccounts
   {
      List&lt; string &gt; m_users;

      public Accounts()
      {
         m_users = new List&lt; string &gt; {
            "marius.bancila",
            "john.doe",
            "anna.kepler"
         };
      }

      #region IDataQuery Members

      public string[] GetUsers()
      {
         return m_users.ToArray();
      }

      public bool GetUsers2(out string[] users)
      {
         users = m_users.ToArray();

         return users.Length &gt; 0;
      }

      #endregion
   }
}
</pre>
<p>Note: If you are trying this example make sure you set the ComVisible attribute to true, either for each type or per assembly (in AssemblyInfo.cs)</p>
<pre name="code" class="csharp">
[assembly: ComVisible(true)]
</pre>
<p>Second, you have to check the &#8220;Register for COM interop&#8221; setting in the Build page of the project properties.</p>
<p>The first thing to do in C++ is importing the .TLB file that was generated by regasm.exe.</p>
<pre name="code" class="cpp">
#import "SampleLibrary.tlb"
using namespace SampleLibrary;
</pre>
<p>If we look in the .TLB file, we can see how the IAccounts interface looks like:</p>
<pre name="code" class="cpp">
struct __declspec(uuid("2f8433fe-4771-4037-b6b2-ed5f6585ed04"))
IAccounts : IDispatch
{
    //
    // Wrapper methods for error-handling
    //

    // Methods:
    SAFEARRAY * GetUsers ( );
    VARIANT_BOOL GetUsers2 (
        SAFEARRAY * * users );
};
</pre>
<p>The following C++ functions, GetUsers1() retrieves the users users list using method GetUsers() from IAccounts. It puts the users in a CStringArray (notice that this container does not have an assignment operator, so the only way to return such an array is with a reference in the parameters list).</p>
<pre name="code" class="cpp">
void GetUsers1(CStringArray&amp; arrUsers)
{
   IAccountsPtr pAccounts(__uuidof(Accounts));

   SAFEARRAY* sarrUsers = pAccounts-&gt;GetUsers();

   _variant_t varUsers;
   varUsers.parray = sarrUsers;
   varUsers.vt = VT_ARRAY | VT_BSTR;

   UnpackBstrArray(varUsers, arrUsers);
   SafeArrayDestroy(sarrUsers);

   pAccounts-&gt;Release();
}
</pre>
<p>UnpackBstrArray() is a function (see below) that extracts the elements of a SAFEARRAY and adds them to a CStringArray.</p>
<p>Function GetUsers2() uses the second method, GetUsers2() from IAccounts. This needs the address of a pointer to a SAFEARRAY (i.e. SAFEARRAY**) that will hold the values returned by the COM method. This time we have to create an empty SAFEARRAY and then pass its address to the COM method. The rest is similar to the previous case.</p>
<pre name="code" class="cpp">
void GetUsers2(CStringArray&amp; arrUsers)
{
   IAccountsPtr pAccounts(__uuidof(Accounts));

   SAFEARRAYBOUND aDim[1];
   aDim[0].lLbound = 0;
   aDim[0].cElements = 0;

   SAFEARRAY* sarrUsers = SafeArrayCreate(VT_BSTR, 1, aDim);

   VARIANT_BOOL ret = pAccounts-&gt;GetUsers2(&amp;sarrUsers);
   if(ret != VARIANT_FALSE)
   {
      _variant_t varUsers;
      varUsers.parray = sarrUsers;
      varUsers.vt = VT_ARRAY | VT_BSTR;
      UnpackBstrArray(varUsers, arrUsers);
   }

   SafeArrayDestroy(sarrUsers);

   pAccounts-&gt;Release();
}
</pre>
<p>The helper method UnpackBstrArray() used previous looks like this:</p>
<pre name="code" class="cpp">
void UnpackBstrArrayHelper(VARIANT* pvarArrayIn, CStringArray* pstrarrValues)
{
   if (!pstrarrValues || !pvarArrayIn || pvarArrayIn->vt == VT_EMPTY)
      return;

   pstrarrValues-&gt;RemoveAll();

   VARIANT* pvarArray = pvarArrayIn;
   SAFEARRAY* parrValues = NULL;

   SAFEARRAYBOUND arrayBounds[1];
   arrayBounds[0].lLbound = 0;
   arrayBounds[0].cElements = 0;

   if((pvarArray-&gt;vt &#038; (VT_VARIANT|VT_BYREF|VT_ARRAY)) == (VT_VARIANT|VT_BYREF) &#038;&#038;
      NULL != pvarArray-&gt;pvarVal &#038;&#038;
      (pvarArray-&gt;pvarVal-&gt;vt &#038; VT_ARRAY))
   {
      pvarArray = pvarArray-&gt;pvarVal;
   }

   if (pvarArray-&gt;vt &#038; VT_ARRAY)
   {
      if (VT_BYREF &amp; pvarArray-&gt;vt)
         parrValues = *pvarArray-&gt;pparray;
      else
         parrValues = pvarArray-&gt;parray;
   }
   else
      return;

   if (parrValues != NULL)
   {
      HRESULT hr = SafeArrayGetLBound(parrValues, 1, &amp;arrayBounds[0].lLbound);
      hr = SafeArrayGetUBound(parrValues, 1, (long*)&amp;arrayBounds[0].cElements);
      arrayBounds[0].cElements -= arrayBounds[0].lLbound;
      arrayBounds[0].cElements += 1;
   }

   if (arrayBounds[0].cElements &gt; 0)
   {
      for (ULONG i = 0; i &lt; arrayBounds[0].cElements; i++)
      {
         LONG lIndex = (LONG)i;
         CString strValue = _T("");

         VARTYPE vType;
         BSTR bstrItem;

         ::SafeArrayGetVartype(parrValues, &amp;vType);
         HRESULT hr = ::SafeArrayGetElement(parrValues, &amp;lIndex, &amp;bstrItem);

         if(SUCCEEDED(hr))
         {
            switch(vType)
            {
            case VT_BSTR:
               strValue = (LPCTSTR)bstrItem;
               break;
            }

            ::SysFreeString(bstrItem);
         }

         pstrarrValues-&gt;Add(strValue);
      }
   }
}

void UnpackBstrArray( const _variant_t &amp;var, CStringArray &amp;strarrValues  )
{
   UnpackBstrArrayHelper( &amp;(VARIANT)const_cast&lt; _variant_t &#038; &gt;(var), &amp;strarrValues );
}
</pre>
<p>Attached you can find a demo project (C# and C++) with the complete example show in this tutorial.</p>
<a class="downloadlink" href="http://mariusbancila.ro/blog/wp-content/plugins/download-monitor/download.php?id=4" title="Version1.0 downloaded 319 times" >output SAFEARRAY** example (319)</a>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/07/23/net-out-string-to-automation-safearray/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Tuva</title>
		<link>http://mariusbancila.ro/blog/2009/07/17/project-tuva/</link>
		<comments>http://mariusbancila.ro/blog/2009/07/17/project-tuva/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 07:39:21 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[fyenman]]></category>
		<category><![CDATA[lectures]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[tuva]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=323</guid>
		<description><![CDATA[Project Tuva is an enhanced video player created by Microsoft Research to freely host the lectures give my Richard Feynman at the Cornell University in the &#8217;60s. Bill Gates saw the lectures two decades ago, was impressed with them and wanted to make them freely available. Now, it finally happened. You can watch them at [...]]]></description>
			<content:encoded><![CDATA[<p>Project Tuva is an enhanced video player created by Microsoft Research to freely host the lectures give my <a href="http://en.wikipedia.org/wiki/Richard_Feynman">Richard Feynman</a> at the Cornell University in the &#8217;60s. Bill Gates saw the lectures two decades ago, was impressed with them and wanted to make them freely available. Now, it finally happened. You can watch them at <a href="http://research.microsoft.com/apps/tools/tuva/index.html">Microsoft Research</a>.</p>
<p>The seven lectures given by professor Feynman are:</p>
<ul>
<li>Law of Gravity</li>
<li>The Relation of Mathematics and Physics</li>
<li>The Great Conservation Principles</li>
<li>Symmetry in Physical Law</li>
<li>The Distinction of Past and Future</li>
<li>Probability and Uncertainty &#8211; The Quantum Mechanical View of Nature</li>
<li>Seeking New Laws</li>
</ul>
<p>These are great lectures given by one of the greatest physicists of the 20th century. They really worth watching.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/07/17/project-tuva/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Arrays in F#</title>
		<link>http://mariusbancila.ro/blog/2008/03/26/arrays-in-f/</link>
		<comments>http://mariusbancila.ro/blog/2008/03/26/arrays-in-f/#comments</comments>
		<pubDate>Wed, 26 Mar 2008 08:31:31 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=109</guid>
		<description><![CDATA[Yesterday I wrote about list in F#. Today I&#8217;ll write about arrays, which unlike lists are a mutable flat storage and cannot be resized. That means you have to create a new array if you want to remove or add elements. Advantages include constant look-up time and the fact that they can store a large [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I wrote about list in F#. Today I&#8217;ll write about arrays, which unlike lists are a mutable flat storage and cannot be resized. That means you have to create a new array if you want to remove or add elements. Advantages include constant look-up time and the fact that they can store a large amount of data.</p>
<p>You can create a literal array in a similar way with the lists, placing the elements between [| |]:</p>
<pre class="prettyprint">
let data1 = [|1;2;3;4|]
printfn "data1: %a" output_any data1
</pre>
<pre class="console">
data1: [|1; 2; 3; 4|]
</pre>
<p>The empty literal array is [||].</p>
<p>To create an array you can either use Array.create or Array.init. They both create and initialize an array, but the second makes a lambda expression, which allows advance initialization possibilities. The following creates an array with 10 elements initialized to 1:
</p>
<pre class="prettyprint">
let data2 = Array.create 10 1
printfn "data2: %a" output_any data2
</pre>
<p>Here is the output:</p>
<pre class="console">
data2: [|1; 1; 1; 1; 1; 1; 1; 1; 1; 1|]
</pre>
<p>The same can be achieved using Array.init:</p>
<pre class="prettyprint">
let data3 = Array.init 10 (fun x -> 1)
printfn "data3: %a" output_any data3
</pre>
<pre class="console">
data3: [|1; 1; 1; 1; 1; 1; 1; 1; 1; 1|]
</pre>
<p>But we can use Array.init to initialize the elements from 1 to N for instance:</p>
<pre class="prettyprint">
let data4 = Array.init 10 (fun x -> x+1)
printfn "data4: %a" output_any data4
</pre>
<pre class="console">
data4: [|1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]
</pre>
<p>The arrays are mutable data structures. Elements are accessed with .[] or .(). The following code shows how to set the elements of an array:</p>
<pre class="prettyprint">
let data5 = Array.create 10 0
for i = 0 to (Array.length data5)-1 do
   data5.[i] <- i+1

printfn "data5: %a" output_any data5
</pre>
<pre class="console">
data5: [|1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]
</pre>
<p>You can iterate over the elements of an array with Array.iter and Array.iteri, the second also providing access to the index of the elements.</p>
<pre class="prettyprint">
data4 |> Array.iter (fun x -> printf "%d " x)
printfn ""

data4 |> Array.iteri (fun i x -> printfn "data4(%d) = %d" i x)
</pre>
<pre class="console">
1 2 3 4 5 6 7 8 9 10
data4(0) = 1
data4(1) = 2
data4(2) = 3
data4(3) = 4
data4(4) = 5
data4(5) = 6
data4(6) = 7
data4(7) = 8
data4(8) = 9
data4(9) = 10
</pre>
<p>Retrieving the length of the array can either be done with Array.length arr or with arr.Length.</p>
<pre class="prettyprint">
for i = 0 to data4.Length-1 do
   printfn "data4(%d) = %d" i data4.(i)
</pre>
<pre class="console">
data4(0) = 1
data4(1) = 2
data4(2) = 3
data4(3) = 4
data4(4) = 5
data4(5) = 6
data4(6) = 7
data4(7) = 8
data4(8) = 9
data4(9) = 10
</pre>
<p>Like the lists, arrays provide mapping that creates a new array by applying a function on all the elements of an array (with Array.map) or two arrays (with Array.map2).</p>
<pre class="prettyprint">
let data6 = data4 |> Array.map (fun x -> x*2)
printfn "data6: %a" output_any data6

let data7 = Array.map2 (fun x y -> x+y) data4 data6
printfn "data7: %a" output_any data7
</pre>
<pre class="console">
data6: [|2; 4; 6; 8; 10; 12; 14; 16; 18; 20|]
data7: [|3; 6; 9; 12; 15; 18; 21; 24; 27; 30|]
</pre>
<p>A copy of an array can be done with Array.copy.</p>
<pre class="prettyprint">
let data7 = Array.copy data6
printfn "data7: %a" output_any data7
</pre>
<pre class="console">
data7: [|2; 4; 6; 8; 10; 12; 14; 16; 18; 20|]
</pre>
<p>Appending elements to an array is also possible with Array.append, but the result is a new array, created by concatenating two arrays.</p>
<pre class="prettyprint">
let data8 = Array.append data7 [|100|]
printfn "data8: %a" output_any data8
</pre>
<pre class="console">
data8: [|2; 4; 6; 8; 10; 12; 14; 16; 18; 20; 100|]
</pre>
<p>The last operation of arrays I'm going to mention here is the folding, which allows applying a function to all the elements of an array, threading an accumulator argument in the process. The following example shows how to compute the sum of the elements of an array.
</p>
<pre class="prettyprint">
let data9 = [|1;2;3;4|]
let sum1 = (Array.fold_left (fun acc x-> x + acc) 0 data9)
let sum2 = (Array.fold_right (fun acc x-> x + acc) data9 0)
printfn "sum1 = %d" sum1
printfn "sum2 = %d" sum2
</pre>
<pre class="console">
sum1 = 10
sum2 = 10
</pre>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2008/03/26/arrays-in-f/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Lists in F#</title>
		<link>http://mariusbancila.ro/blog/2008/03/25/lists-in-f/</link>
		<comments>http://mariusbancila.ro/blog/2008/03/25/lists-in-f/#comments</comments>
		<pubDate>Tue, 25 Mar 2008 08:17:51 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[F# tutorial article list recursive]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=108</guid>
		<description><![CDATA[In this post I will talk about the lists in F#, one of the fundamental concepts of the language. What should be said from the very beginning is that list are imutable single linked list. That means whenever you change a list, a new list is created. You can declare a list in the following [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I will talk about the lists in F#, one of the fundamental concepts of the language. What should be said from the very beginning is that list are imutable single linked list. That means whenever you change a list, a new list is created.</p>
<p>You can declare a list in the following ways:</p>
<p><PRE class="prettyprint">
let list1 = [1;2;3;4]
let list2 = 5::6::7::8::[]
</pre></p>
<p>To print the content of the list you can do this:</p>
<p><PRE class="prettyprint">
printfn &#8220;list1: %a&#8221; output_any list1
printfn &#8220;list2: %a&#8221; output_any list2
</pre></p>
<pre class="console">
list1: [1; 2; 3; 4]
list2: [5; 6; 7; 8]
</pre></p>
<p>You can concatenate two lists with operator @:</p>
<p><PRE class="prettyprint">
let list3 = list1 @ list2
printfn "list3: %a" output_any list3
</pre></p>
<pre class="console">
list3: [1; 2; 3; 4; 5; 6; 7; 8]
</pre>
<p>and you can append elements to the beginning of the list with operator ::</p>
<p><PRE class="prettyprint">
let list4 = -1::0::list3
printfn "list4: %a" output_any list4
</pre></p>
<pre class="console">
list4: [-1; 0; 1; 2; 3; 4; 5; 6; 7; 8]
</pre>
<p>You can also use the List (defined in Microsoft.FSharp.Code) functionality to print a list by iterating over its elements:</p>
<p><PRE class="prettyprint">
list3: [1; 2; 3; 4; 5; 6; 7; 8]
</pre><br />
<PRE class="console">
1 2 3 4
</pre></p>
<p>The same can be achieved using the pipe operator:</p>
<p><PRE class="prettyprint">
list1 |> List.iter (fun x -> printf "%d " x)
</pre></p>
<p>You can also iterate and get the index of the list elements, with List.iteri:</p>
<pre class="prettyprint">
list1 |> List.iteri (fun i x -> printfn "list1[%d] : %d " i x)
</pre><br />
<PRE class="console">
list1[0] : 1
list1[1] : 2
list1[2] : 3
list1[3] : 4
</pre></p>
<p>List have a special representation, a head followed by a tail, that is in turn another list (including empty list []). Let's consider the list [1;2;3]. It has the head 1, and the tail [2;3]. The tail, in turn, has the head 2 and the tail [3]. This tail has the head 3 and the tail [], which is the empty list.<br />
You can see the head and tail of a list with List.hd and List.td:</p>
<p><PRE class="prettyprint">
printfn "head list1: %a" output_any (List.hd list1)
printfn "tail list1: %a" output_any (List.tl list1)
</pre></p>
<p>The ouput for list1 [1;2;3] is:</p>
<pre class="console">
head list1: 1
tail list1: [2;3]
</pre>
<p>Enough with basic things. Let's try working with lists.</p>
<h3>1. Minimum and maximum from a list</h3>
<p>We can compute the maximum (or minimum) of a list using the following algorithm:</p>
<ul>
<li>if the list is empty, indicate error</li>
<li>if the list has only one element, that is the maximum (or minimum)</li>
<li>if the list has at least to elements, compute the maximum between that element and the maximum from the rest of the list</li>
</ul>
<p>That sounds like a recursive operation, which can be simply put in F# like this:</p>
<p><PRE class="prettyprint">
let rec greatest_element l =
    match l with
    | [] -> failwith "empty list"
    | [x] -> x
    | x::rest -> max x (greatest_element rest)

let rec smallest_element l =
    match l with
    | [] -> failwith "empty list"
    | [x] -> x
    | x::rest -> min x (smallest_element rest)
</pre></p>
<p>We can use that like this:</p>
<p><PRE class="prettyprint">
let list1 = [1;2;3;4;-4;-3;-2;-1]
let list2 = []   

try
   printfn "maximum from list1: %d" (greatest_element list1)
   printfn "minimum from list1: %d" (smallest_element list1)

   printfn "maximum from list2: %d" (greatest_element list2)
   printfn "minimum from list2: %d" (smallest_element list2)
with
   Failure msg ->
      printfn "Error: %s" msg
</pre></p>
<p>and the output would be:</p>
<pre class="console">
maximum from list1: 4
minimum from list1: -4
Error: empty list
</pre></p>
<h3>2. Reversing a list</h3>
<p>How would we reverse a list? We should take the last element and append to it the one before the last. To the new list we append the one before the one before the end, etc. That again sounds recursive.</p>
<p><PRE class="prettyprint">
let rec revert_list l =
   match l with
   | [] -> []
   | x::rest -> (revert_list rest) @ [x]

let list1 = [1;2;3;4;-4;-3;-2;-1]

printfn "list1: %a" output_any list1
printfn "list2: %a" output_any (revert_list list1)
</pre></p>
<p>And here is the output:</p>
<p><PRE class="console">
list1: [1; 2; 3; 4; -4; -3; -2; -1]
list2: [-1; -2; -3; -4; 4; 3; 2; 1]
</pre></p>
<h3>3. Inserting in a list</h3>
<p>So how could we insert an element in a list, before or after a specified element? We can use the following algorithm:</p>
<ul>
<li>if the list is empty, the new list has one element (the one to insert)</li>
<li>else, if the head is the element we are looking for, create a list, with the new element either before the head, or between the head and the tail</li>
<li>else, if the head is not the element we are looking for, append the head to a list created by inserting the new element in the tail.</li>
</ul>
<p>You got that right, recursion again.</p>
<p><PRE class="prettyprint">
let rec insert_after elem newelem l =
    match l with
    | [] -> [newelem]
    | x::rest -> if x = elem then
                    (x::newelem::rest)
                 else
                     x::(insert_after elem newelem rest)

let rec insert_before elem newelem l =
    match l with
    | [] -> [newelem]
    | x::rest -> if x = elem then
                    (newelem::x::rest)
                 else
                    x::(insert_before elem newelem rest)        

let list1 = [1;2;3;4;-4;-3;-2;-1]
let list2 = insert_after 4 6 list1
let list3 = insert_before 6 5 list2

printfn "list1: %a" output_any list1
printfn "list2: %a" output_any list2
printfn "list3: %a" output_any list3
</pre></p>
<p>And the output is:</p>
<pre class="console">
list1: [1; 2; 3; 4; -4; -3; -2; -1]
list2: [1; 2; 3; 4; 6; -4; -3; -2; -1]
list3: [1; 2; 3; 4; 5; 6; -4; -3; -2; -1]
</pre></p>
<h3>4. Removing elements from a list</h3>
<p>As a last exercise, let's consider the removing of elements from a list. The following steps can be used to remove elements:</p>
<ul>
<li>if the list is empty, return an empty list</li>
<li>if the list is not empty and the head meets the removing criteria, return a list obtained by reiterating the algorithm on the tail of the list</li>
<li>if the list is not empty and the head does not meet the removing criteria, return a list obtained by appending the head to a list optained by reiterating the algorithm on the tail of the list</li>
</ul>
<p><PRE class="prettyprint">
let rec remove_if l predicate =
    match l with
    | [] -> []
    | x::rest -> if predicate(x) then
                    (remove_if rest predicate)
                 else
                     x::(remove_if rest predicate)
</pre></p>
<p>The great thing about this implementation is that we can pass a lambda expression as a predicate, and use it to specify the criteria for removing elements. We can remove like that, for instance, the odd elements, or the even elements, or the negative elements. Here is some sample code:</p>
<p><PRE class="prettyprint">
let list1 = [1;2;3;4;-4;-3;-2;-1]

let list2 = remove_if list1 (fun x -> (abs x &#038;&#038;&#038;1) = 1)
let list3 = remove_if list1 (fun x -> (abs x &#038;&#038;&#038;1) = 0)
let list4 = remove_if list1 (fun x -> x < 0)

printfn "%a" output_any list1
printfn "%a" output_any list2
printfn "%a" output_any list3
printfn "%a" output_any list4
</pre></p>
<p>The output for this sample is:</p>
<p><PRE class="console">
[1; 2; 3; 4; -4; -3; -2; -1]
[2; 4; -4; -2]
[1; 3; -3; -1]
[1; 2; 3; 4]
</pre></p>
<p>I hope this will help you to get a grip on how you can work on lists in F#.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2008/03/25/lists-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

