Get a string from a COM Server

To receive a string from a COM server:

To receive a string from a COM object, it is necessary for the object to create the memory for the string, and for the client to destroy the memory.  To make this happen, the client must pass a pointer to the server.  The server will create a string, and assign the string to the pointer passed in by the client.  The client must then copy the contents of the string to some local variable, and free the string.  If this is not done, the returned string will be leaked.

The following code is an example of getting a string value from a COM server:

 

1      BSTR temp_str;
2      string ret_string;
3      pObject->GetString(&temp_str);
4      ret_string = (_bstr_t) temp_str;
5      SysFreeString(temp_str);

 

Explanation:

Line 1 – Declare a BSTR type variable, which will be the parameter that gets passed to the server.  A BSTR is a somewhat confusing Windows specific data type that fundamentally a pointer to a character. ( char * )

Here are the specifics on a BSTR:

typedef  OLECHAR __RPC_FAR *BSTR;                 // BSTR is a pointer to OLECHAR

typedef void __RPC_FAR * RPC_IF_HANDLE;   // I can’t say that I understand this construction – it is the definition for __RPC_FAR

// which makes it look like it is a void pointer?

typedef    char    OLECHAR;                                          // OLECHAR is a char


So, if you follow all of that, BSTR is a char*.

Line 2 – create a string variable to store the data locally.

Line 3 – call the server function, passing the BSTR (char*) to the function. The server will create the string, and the pointer will be pointing to it when the function returns. This deserves a little more explanation. pObject represents a smartpointer to a COM object, which has a method named “GetString”, which takes a BSTR* parameter. The COM object pointed to by pObject would have to have been created prior to this code.  Also note, we pass the address of our BSTR to the function.  (the address is a **char at this point).

Line 4 – copy the string pointed to by the BSTR to our local string variable.

Line 5 – free the string that is attached to the BSTR. This will free the memory that was allocated inside the server.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>