StackBstrT

 

// Template class to generate a BSTR from a static wide string

// without touching the heap.  Use this class via the StackBstrVar and

// StackBstr macros.

template <uint32 string_bytes>

class StackBstrT {

 public:

  // Try to stay as const as we can in an attempt to avoid someone

  // using the class incorrectly (e.g. by supplying a variable instead

  // of a verbatim string.  We also have an assert in the constructor

  // as an extra runtime check since the const-ness only catches one case.

  explicit StackBstrT(const wchar_t* const str) {

    // The BSTR API uses UINT, but we prefer uint32.

    // Make sure we'll know about it if these types don't match.

    COMPILE_ASSERT(sizeof(uint32) == sizeof(UINT), UintToUint32);

    COMPILE_ASSERT(sizeof(wchar_t) == sizeof(OLECHAR), WcharToOlechar);

 

    // You shouldn't pass string pointers to this constructor since

    // there's no way for the compiler to calculate the length of the

    // string (string_bytes will be equal to pointer size in those cases).

    DCHECK(lstrlenW(str) == (string_bytes / sizeof(bstr_.str_[0])) - 1) <<

        "not expecting a string pointer";

    memcpy(bstr_.str_, str, string_bytes);

    bstr_.len_ = string_bytes - sizeof(wchar_t);

  }

 

  operator BSTR() {

    return bstr_.str_;

  }

 

 protected:

  struct BstrInternal {

    uint32 len_;

    wchar_t str_[string_bytes / sizeof(wchar_t)];

  } bstr_;

};

 

 

// Use this macro to generate an inline BSTR from a wide string.

// This is about 6 times faster than using the SysAllocXxx functions to

// allocate a BSTR and helps with keeping heap fragmentation down.

// Example:

//  DoBstrStuff(StackBstr(L"This is my BSTR"));

// Where DoBstrStuff is:

//  HRESULT DoBstrStuff(BSTR bstr) { ... }

#define StackBstr(str) /

  static_cast<BSTR>(StackBstrT<sizeof(str)>(str))

 

// If you need a named BSTR variable that's based on a fixed string

// (e.g. if the BSTR is used inside a loop or more than one place),

// use StackBstrVar to declare a variable.

// Example:

//   StackBstrVar(L"my_property", myprop);

//   for (int i = 0; i < objects.length(); ++i)

//     ProcessValue(objects[i].GetProp(myprop));  // GetProp accepts BSTR

#define StackBstrVar(str, var) /

  StackBstrT<sizeof(str)> var(str)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值