Variant and cstring convert each other

Source: Internet
Author: User

The variant type is often used to pass parameters to com objects or receive values returned from COM objects. You can also write methods that return the variant type by yourself. The input parameters (for example, in an automated operation, dependency on the method you call) of the possible (and often) Type of dependency returned by the function. Idispatch: invoke may return a result that contains the variant type, such as byte, word, float, double, date, and BSTR, (For details, see the definition of the variant structure on msdn ). In the following example, assume that the type is a variant of BSTR, that is, the value in the string is referenced through bsrtval, and its advantage is that in ANSI applications, there is a constructor that converts the value referenced by lpcwchar to a cstring (see section BSTR-to-cstring ). In Unicode mode, it will become a standard cstring constructor. For more information, see warn about the default: widechartomultibyte conversion and whether you think it is acceptable (in most cases, you will be satisfied ). Variant vadata;

Vadata = m_com.yourmethodhere ();

Assert (vadata. Vt = vt_bstr );

Cstring strdata (vadata. bstrval );

You can also create more common conversion routines based on different VT domains. For this reason, you may consider:

Cstring varianttostring (variant * VA)

{

Cstring S;

Switch (va-> VT)

{/* Vt */

Case vt_bstr:

Return cstring (vadata-> bstrval );

Case vt_bstr | vt_byref:

Return cstring (* vadata-> pbstrval );

Case vt_i4:

S. Format (_ T ("% d"), va-> lval );

Return S;

Case vt_i4 | vt_byref:

S. Format (_ T ("% d"), * va-> plval );

Case vt_r8:

S. Format (_ T ("% F"), va-> dblval );

Return S;

... The remaining type conversion is done by the reader.

Default:

Assert (false); // unknown variant type (this assert is optional)

Return cstring ("");

}/* Vt */

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.