Passing String To and From COM Components

Many of the IShellLink methods use strings. Consider for example the declaration of GetDescription()

ITPro Today

July 19, 2004

2 Min Read
ITPro Today logo

Many of the IShellLink methods use strings. Consider for example the declaration of GetDescription()

 

A COM Wrapper Method Using Strings

void GetDescription(


  [Out(), MarshalAs(UnmanagedType.LPWStr)] 


          StringBuilder pszName, int cchMaxName);


 

The method returns a string using a StringBuilder representing a WChar array with a specific size. A MarshalAs attribute is used to tell the .NET Framework how to handle the native unmanaged type. To call GetDescription() from C#, you need to set up a StringBuilder object with the required size and call the method as shown below:

 

Getting a Returned String from a COM Wrapper Method

 

StringBuilder buffer = new StringBuilder(5000);

shellLink.GetWorkingDirectory(buffer, buffer.Capacity);

workingDirectory = buffer.ToString();

 

StringBuilder.Capacity denotes the size of the WChar buffer. The value is passed to the class constructor, and you can use any value you need. In my case, 5000 characters is more than enough space for any strings that GetWorkingDirectory() will be returning.

To pass a string to a method, such as with SetWorkingDirectory(), you can just use a plain String object as shown  below..

Pasing a String to a COM Wrapper Method

String workingDirectory = "MyDirectory";


shellLink.SetWorkingDirectory(workingDirectory);

Happy Coding !

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like