1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_WIN_SCOPED_BSTR_H_
6 #define BASE_WIN_SCOPED_BSTR_H_
11 #include "base/base_export.h"
12 #include "base/logging.h"
13 #include "base/strings/string16.h"
18 // Manages a BSTR string pointer.
19 // The class interface is based on scoped_ptr.
20 class BASE_EXPORT ScopedBstr
{
22 ScopedBstr() : bstr_(NULL
) {
25 // Constructor to create a new BSTR.
27 // NOTE: Do not pass a BSTR to this constructor expecting ownership to
28 // be transferred - even though it compiles! ;-)
29 explicit ScopedBstr(const char16
* non_bstr
);
32 // Give ScopedBstr ownership over an already allocated BSTR or NULL.
33 // If you need to allocate a new BSTR instance, use |allocate| instead.
34 void Reset(BSTR bstr
= NULL
);
36 // Releases ownership of the BSTR to the caller.
39 // Creates a new BSTR from a 16-bit C-style string.
41 // If you already have a BSTR and want to transfer ownership to the
42 // ScopedBstr instance, call |reset| instead.
44 // Returns a pointer to the new BSTR, or NULL if allocation failed.
45 BSTR
Allocate(const char16
* str
);
47 // Allocates a new BSTR with the specified number of bytes.
48 // Returns a pointer to the new BSTR, or NULL if allocation failed.
49 BSTR
AllocateBytes(size_t bytes
);
51 // Sets the allocated length field of the already-allocated BSTR to be
52 // |bytes|. This is useful when the BSTR was preallocated with e.g.
53 // SysAllocStringLen or SysAllocStringByteLen (call |AllocateBytes|) and then
54 // not all the bytes are being used.
56 // Note that if you want to set the length to a specific number of
57 // characters, you need to multiply by sizeof(wchar_t). Oddly, there's no
58 // public API to set the length, so we do this ourselves by hand.
60 // NOTE: The actual allocated size of the BSTR MUST be >= bytes. That
61 // responsibility is with the caller.
62 void SetByteLen(size_t bytes
);
64 // Swap values of two ScopedBstr's.
65 void Swap(ScopedBstr
& bstr2
);
67 // Retrieves the pointer address.
68 // Used to receive BSTRs as out arguments (and take ownership).
69 // The function DCHECKs on the current value being NULL.
70 // Usage: GetBstr(bstr.Receive());
73 // Returns number of chars in the BSTR.
74 size_t Length() const;
76 // Returns the number of bytes allocated for the BSTR.
77 size_t ByteLength() const;
79 operator BSTR() const {
87 // Forbid comparison of ScopedBstr types. You should never have the same
88 // BSTR owned by two different scoped_ptrs.
89 bool operator==(const ScopedBstr
& bstr2
) const;
90 bool operator!=(const ScopedBstr
& bstr2
) const;
91 DISALLOW_COPY_AND_ASSIGN(ScopedBstr
);
97 #endif // BASE_SCOPED_BSTR_H_