<?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>Random Musings&#187; tlbimp</title> <atom:link href="http://www.nslms.com/tag/tlbimp/feed/" rel="self" type="application/rss+xml" /><link>http://www.nslms.com</link> <description></description> <lastBuildDate>Wed, 06 Jul 2011 20:47:34 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3</generator> <item><title>Microsoft&#8217;s Tlbimp creates leaky BSTR signatures</title><link>http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link> <comments>http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/#comments</comments> <pubDate>Thu, 13 Mar 2008 23:30:49 +0000</pubDate> <dc:creator>RyanG</dc:creator> <category><![CDATA[C# coding]]></category> <category><![CDATA[BSTR]]></category> <category><![CDATA[in/out]]></category> <category><![CDATA[linkedin]]></category> <category><![CDATA[memory leak]]></category> <category><![CDATA[tlbimp]]></category> <guid
isPermaLink="false">http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/</guid> <description><![CDATA[This one confounded me when I first discovered it, and I&#8217;ve recently been reminded about it. For the sake of remembering the details, and hopefully helping someone else out I&#8217;m going to document it here. The problem is this. When you have a COM library that you need to use from a C# app, you [...]]]></description> <content:encoded><![CDATA[<div
class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a
href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nslms.com%2F2008%2F03%2F13%2Fmicrosofts-tlbimp-creates-leaky-bstr-signatures%2F"><br
/> <img
src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nslms.com%2F2008%2F03%2F13%2Fmicrosofts-tlbimp-creates-leaky-bstr-signatures%2F&amp;source=rjgeyer&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br
/> </a></div><p>This one confounded me when I first discovered it, and I&#8217;ve recently been reminded about it.  For the sake of remembering the details, and hopefully helping someone else out I&#8217;m going to document it here.</p><p>The problem is this.  When you have a COM library that you need to use from a C# app, you import it as a reference.  In the background the Microsoft.NET wizards do their magic by running the <a
href="http://msdn2.microsoft.com/en-us/library/tt0cf3sx(VS.80).aspx">Tlbimp.exe</a> to generate a managed DLL with all of the objects and interfaces from the COM library.  You proceed to use the code that Microsoft so conveniently converted for you fully confident that all is well.</p><p>But it&#8217;s not.  See, suppose your COM library has a method that returns a <strong>BSTR</strong> via an [out] parameter, or perhaps it defines an interface for a listener your managed code must implement.  Suddenly there is the potential for a serious memory leak!</p><p>See, a <strong>BSTR</strong> in unmanaged code aren&#8217;t just any normal string. <strong>BSTR</strong>&#8216;s are allocated by the system by calling <strong>SysAllocString</strong> and subsequently released by calling <strong>SysFreeString</strong>.  This poses a problem for managed code if you aren&#8217;t careful.  Take the following listener interface for example.</p><p
style="font-family: italic; font-size: 10px">*Interface names and GUID&#8217;s changed to protect the innocent</p><pre line="1" lang="idl">
interface IImplementMeListener : IDispatch{
[
id(0x000000C9)
]
HRESULT _stdcall notify([in] TEventType eventType, [in] BSTR data );
};</pre><p>The Tlbimp.exe generates a managed assembly with the following signature for this same method.</p><pre line="1" lang="csharp">
[ComImport, TypeLibType((short) 0x10c0), Guid("00000000-0000-0000-0000-000000000000")]
public interface IImplementMeListener
{
    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0xc9)]
    void notify([In, ComAliasName("ExampleLib.TEventType")] TEventType eventType,
        [In, MarshalAs(UnmanagedType.BStr)] string data);
}</pre><p>Which means when you implement this interface in your managed class, you&#8217;ll just have <strong>String</strong> as the data type for the second parameter.  Which might look like this.</p><pre line="1" lang="csharp">
class MyManagedListener : ExampleLib.IImplementMeListener{
    public void notify(ExampleLib.TEventType eventType, String data)
    {
        DoSomethingWithData(data);
    }
}</pre><p>So this is what happens.</p><p>1) Your COM library allocates the string to pass into your listener using <strong>SysAllocString</strong>.</p><p>2) Your COM library passes the newly allocated string into your managed app by calling the <strong>notify</strong> method of your listener.</p><p>3) Your managed app does whatever it&#8217;s going to do with the string, then returns.</p><p>Normally in a fully managed app this would be no problem, when the reference count to the string finally reaches 0, the garbage collector sweeps it up and the memory is reclaimed.  However, in this case we have a problem.  The COM library allocated the string, and passed it into your managed app, and it&#8217;s responsibility for that string ends there.  The expectation is that the client will release the <strong>BSTR</strong> by calling <strong>SysFreeString</strong>.  Clearly we can&#8217;t explicitly do that to the managed <strong>String</strong> type.</p><p>So what do we do?  We rewrite the part of the assembly that Tlbimp.exe made for us, and adjust our listener implementation slightly.</p><p>This is how I did it, though there may be better ways.</p><p>1) Use a disassembler to view the code of the Tlbimp.exe generated assembly for your COM library.  I used, <a
href="http://www.aisto.com/roeder/dotnet/">Lutz&#8217;s Reflector</a>.</p><p>2) Copy the code for the entire library into a *.cs file, then change just the signature of the method you&#8217;re concerned with.</p><p>The new signature should look like this.</p><pre line="1" lang="csharp">
[ComImport, Guid("00000000-0000-0000-0000-000000000000"), TypeLibType((short) 0x10c0)]
public interface IImplementMeListener
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0xc9)]
    void notify([In, ComAliasName("ExampleLib.TEventType")] TEventType eventType,
        [In] IntPtr data);
}</pre><p>And your implementing class changes to this.</p><pre line="1" lang="csharp">
class MyManagedListener : ExampleLib.IImplementMeListener{
    public void notify(ExampleLib.TEventType eventType, IntPtr data)
    {
        String dataStr = Marshal.PtrToStringBSTR(data);
        DoSomethingWithData(dataStr);
        Marshal.FreeBSTR(data);
    }
}</pre><p>This is not particularly tricky wizardry.  All we&#8217;re doing is marshaling the input value from the library as an <strong>IntPtr</strong> instead of a managed <strong>String</strong>.  This allows us to explicitly release it using the <strong>System.Runtime.InteropServices.Marshal.FreeBSTR</strong> method, just like the library expects us to do.</p><p>Hopefully, this will save you some hastle, and avoid a potentially large memory leak.</p><div
class="shr-bookmarks shr-bookmarks-center"><ul
class="socials"><li
class="shr-blogger"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=219&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Blog this on Blogger">Blog this on Blogger</a></li><li
class="shr-comfeed"> <a
href="http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/feed" rel="nofollow" class="external" title="Subscribe to the comments for this post?">Subscribe to the comments for this post?</a></li><li
class="shr-facebook"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=5&amp;tags=&amp;ctype=" rel="nofollow" title="Share this on Facebook">Share this on Facebook</a></li><li
class="shr-linkedin"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=88&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Share this on LinkedIn">Share this on LinkedIn</a></li><li
class="shr-mail"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s%20Tlbimp%20creates%20leaky%20BSTR%20signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=201&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a></li><li
class="shr-posterous"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=210&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Post this to Posterous">Post this to Posterous</a></li><li
class="shr-twitter"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=%2524%257Btitle%257D%2B-%2B%2524%257Bshort_link%257D&amp;service=7&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a></li><li
class="shr-digg"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=3&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Digg this!">Digg this!</a></li><li
class="shr-friendfeed"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=43&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Share this on FriendFeed">Share this on FriendFeed</a></li><li
class="shr-googlereader"> <a
href="http://www.shareaholic.com/api/share/?title=Microsoft%27s+Tlbimp+creates+leaky+BSTR+signatures&amp;link=http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/&amp;notes=This%20one%20confounded%20me%20when%20I%20first%20discovered%20it%2C%20and%20I%27ve%20recently%20been%20reminded%20about%20it.%20%20For%20the%20sake%20of%20remembering%20the%20details%2C%20and%20hopefully%20helping%20someone%20else%20out%20I%27m%20going%20to%20document%20it%20here.%0D%0A%0D%0AThe%20problem%20is%20this.%20%20When%20you%20have%20a%20COM%20library%20that%20you%20need%20to%20use%20from%20a%20C%23%20app%2C%20you%20im&amp;short_link=&amp;shortener=google&amp;shortener_key=&amp;v=1&amp;apitype=1&amp;apikey=8afa39428933be41f8afdb8ea21a495c&amp;source=Shareaholic&amp;template=&amp;service=207&amp;tags=&amp;ctype=" rel="nofollow" class="external" title="Add this to Google Reader">Add this to Google Reader</a></li></ul><div
style="clear: both;"></div><div
class="shr-getshr" style="visibility:hidden;font-size:10px !important"><a
target="_blank" href="http://www.shareaholic.com/?src=pub">Get Shareaholic</a></div><div
style="clear: both;"></div></div> ]]></content:encoded> <wfw:commentRss>http://www.nslms.com/2008/03/13/microsofts-tlbimp-creates-leaky-bstr-signatures/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> </channel> </rss>
