//
archives

BSTR

This category contains 6 posts

How to Store Binary Data in a BSTR.

1. Introduction 1.1 A BSTR is flexible in the sense that not only can you store a character string in it, you can also store binary data. 1.2 This programming tip presents sample code which demonstrates how this can be done. 2. The SysAllocStringByteLen() API. 2.1 Normally, when you want to allocate a BSTR, you … Continue reading

The Importance of Proper BSTR Allocation.

1. Introduction. 1.1 Note that code like the following : BSTR bstr = L”My BSTR”; does not allocate a BSTR. 1.2 To allocate a BSTR, you must use the ::SysAllocString() API : BSTR bstr = ::SysAllocString(L”My BSTR”); 2. Explanation. 2.1 We can verify this with a call to the ::SysStringByteLen() API : UINT uiLen = ::SysStringByteLen(bstr); … Continue reading

Misunderstanding IDL Parameter Direction Leading to BSTR Memory Leakage.

1. Introduction. 1.1 Just yesterday a Visual C# Forum Member posed an interesting question. The post can be found here : Possible BSTR memory leak 1.2 Basically, he designed a COM class (in IDL) that takes charge of acquiring data from some source. He also defined a callback interface that is to be implemented by clients. An instance … Continue reading

Using BSTR in Managed Code Part 2

1. Introduction. 1.1 In part 1 of this series of blogs, I demonstrated how to use BSTRs in managed code complete with example codes that focuses on passing BSTRs from managed code to unmanaged code. 1.2 In this part 2, I shall provide example codes that demonstrate the receiving of BSTRs from unmanaged code. 1.3 … Continue reading

Using BSTR in Managed Code Part 1

1. Introduction. 1.1 The COM BSTR may be used within managed code for various purposes including the exchanging of strings to and from unmanaged code. 1.2 There are several ways to work with BSTRs and these are listed in summary below : Using Marshal Class methods (e.g. Marshal.PtrToStringBSTR(), Marshal.StringToBSTR(), Marshal.FreeBSTR()). Using Unmanaged APIs (e.g. SysAllocString(), SysFreeString(), etc). … Continue reading

C# Interop : How to return a VARIANT from an Unmanaged Function

1. To return a VARIANT from an unmanaged API, it must be returned as a VARIANT pointer and the equivalent C# declaration for the API must indicate a return type of IntPtr. For example : __declspec(dllexport) VARIANT* __stdcall MyFunction(); The C# declaration for MyFunction() would be something like : [DllImport(@”MyDLL.dll”, CallingConvention = CallingConvention.StdCall)] static extern IntPtr … Continue reading