views:

338

answers:

1

I'm using a third-party COM library from C#.

There are get/set methods that take a parameter of type VARIANT (type VT_BSTR). In the .NET wrapper, these parameters appear as type object, i.e.

object getValue();
void setValue( object val );

The getValue method works ok, I perform a simple cast of the object to type string:

string str = (string)comObject.getValue();

but setting the string in a similar way doesn't:

string str = "test";
comObject.setValue( str );

The third party library doesn't like this and generates an exception. It must be expecting a VARIANT of type VT_BSTR (as this works from native C++). So my question is, how do I create one of these in C#?

I've been looking at methods like Marshal.GetNativeVariantForObject, but documentation on correct usage of this seems a bit thin on the ground, so any example code would be useful.

+2  A: 

Use the BStrWrapper class:

comObject.setValue(new BStrWrapper(str));
SLaks