VirtualBox

source: vbox/trunk/include/VBox/com/array.h@ 49765

Last change on this file since 49765 was 49765, checked in by vboxsync, 11 years ago

array.h: SafeArray(const SafeArray&) has to implicitly call this->Copy(...) instead of Copy(...), because inheritance isn't working as expected here (C++-FAQ[35.19] http://www.parashift.com/c++-faq-lite/nondependent-name-lookup-members.html)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 51.3 KB
Line 
1/** @file
2 * MS COM / XPCOM Abstraction Layer - Safe array helper class declaration.
3 */
4
5/*
6 * Copyright (C) 2006-2013 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 *
16 * The contents of this file may alternatively be used under the terms
17 * of the Common Development and Distribution License Version 1.0
18 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
19 * VirtualBox OSE distribution, in which case the provisions of the
20 * CDDL are applicable instead of those of the GPL.
21 *
22 * You may elect to license modified versions of this file under the
23 * terms and conditions of either the GPL or the CDDL or both.
24 */
25
26#ifndef ___VBox_com_array_h
27#define ___VBox_com_array_h
28
29/** @defgroup grp_COM_arrays COM/XPCOM Arrays
30 * @{
31 *
32 * The COM/XPCOM array support layer provides a cross-platform way to pass
33 * arrays to and from COM interface methods and consists of the com::SafeArray
34 * template and a set of ComSafeArray* macros part of which is defined in
35 * VBox/com/defs.h.
36 *
37 * This layer works with interface attributes and method parameters that have
38 * the 'safearray="yes"' attribute in the XIDL definition:
39 * @code
40
41 <interface name="ISomething" ...>
42
43 <method name="testArrays">
44 <param name="inArr" type="long" dir="in" safearray="yes"/>
45 <param name="outArr" type="long" dir="out" safearray="yes"/>
46 <param name="retArr" type="long" dir="return" safearray="yes"/>
47 </method>
48
49 </interface>
50
51 * @endcode
52 *
53 * Methods generated from this and similar definitions are implemented in
54 * component classes using the following declarations:
55 * @code
56
57 STDMETHOD(TestArrays)(ComSafeArrayIn(LONG, aIn),
58 ComSafeArrayOut(LONG, aOut),
59 ComSafeArrayOut(LONG, aRet));
60
61 * @endcode
62 *
63 * And the following function bodies:
64 * @code
65
66 STDMETHODIMP Component::TestArrays(ComSafeArrayIn(LONG, aIn),
67 ComSafeArrayOut(LONG, aOut),
68 ComSafeArrayOut(LONG, aRet))
69 {
70 if (ComSafeArrayInIsNull(aIn))
71 return E_INVALIDARG;
72 if (ComSafeArrayOutIsNull(aOut))
73 return E_POINTER;
74 if (ComSafeArrayOutIsNull(aRet))
75 return E_POINTER;
76
77 // Use SafeArray to access the input array parameter
78
79 com::SafeArray<LONG> in(ComSafeArrayInArg(aIn));
80
81 for (size_t i = 0; i < in.size(); ++ i)
82 LogFlow(("*** in[%u]=%d\n", i, in[i]));
83
84 // Use SafeArray to create the return array (the same technique is used
85 // for output array parameters)
86
87 SafeArray<LONG> ret(in.size() * 2);
88 for (size_t i = 0; i < in.size(); ++ i)
89 {
90 ret[i] = in[i];
91 ret[i + in.size()] = in[i] * 10;
92 }
93
94 ret.detachTo(ComSafeArrayOutArg(aRet));
95
96 return S_OK;
97 }
98
99 * @endcode
100 *
101 * Such methods can be called from the client code using the following pattern:
102 * @code
103
104 ComPtr<ISomething> component;
105
106 // ...
107
108 com::SafeArray<LONG> in(3);
109 in[0] = -1;
110 in[1] = -2;
111 in[2] = -3;
112
113 com::SafeArray<LONG> out;
114 com::SafeArray<LONG> ret;
115
116 HRESULT rc = component->TestArrays(ComSafeArrayAsInParam(in),
117 ComSafeArrayAsOutParam(out),
118 ComSafeArrayAsOutParam(ret));
119
120 if (SUCCEEDED(rc))
121 for (size_t i = 0; i < ret.size(); ++ i)
122 printf("*** ret[%u]=%d\n", i, ret[i]);
123
124 * @endcode
125 *
126 * For interoperability with standard C++ containers, there is a template
127 * constructor that takes such a container as argument and performs a deep copy
128 * of its contents. This can be used in method implementations like this:
129 * @code
130
131 STDMETHODIMP Component::COMGETTER(Values)(ComSafeArrayOut(int, aValues))
132 {
133 // ... assume there is a |std::list<int> mValues| data member
134
135 com::SafeArray<int> values(mValues);
136 values.detachTo(ComSafeArrayOutArg(aValues));
137
138 return S_OK;
139 }
140
141 * @endcode
142 *
143 * The current implementation of the SafeArray layer supports all types normally
144 * allowed in XIDL as array element types (including 'wstring' and 'uuid').
145 * However, 'pointer-to-...' types (e.g. 'long *', 'wstring *') are not
146 * supported and therefore cannot be used as element types.
147 *
148 * Note that for GUID arrays you should use SafeGUIDArray and
149 * SafeConstGUIDArray, customized SafeArray<> specializations.
150 *
151 * Also note that in order to pass input BSTR array parameters declared
152 * using the ComSafeArrayIn(IN_BSTR, aParam) macro to the SafeArray<>
153 * constructor using the ComSafeArrayInArg() macro, you should use IN_BSTR
154 * as the SafeArray<> template argument, not just BSTR.
155 *
156 * Arrays of interface pointers are also supported but they require to use a
157 * special SafeArray implementation, com::SafeIfacePointer, which takes the
158 * interface class name as a template argument (e.g. com::SafeIfacePointer
159 * <IUnknown>). This implementation functions identically to com::SafeArray.
160 */
161
162#ifdef VBOX_WITH_XPCOM
163# include <nsMemory.h>
164#endif
165
166 /* Type traits are a C++ 11 feature, so not available everywhere (yet). */
167 /* Only GCC 4.6 or newer. */
168#if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 406) \
169 /* Only MSVC++ 16.0 (Visual Studio 2010) or newer. */ \
170 || (defined(_MSC_VER) && (_MSC_VER >= 1600))
171 #define VBOX_WITH_TYPE_TRAITS
172#endif
173
174#ifdef VBOX_WITH_TYPE_TRAITS
175# include <type_traits>
176#endif
177
178#include "VBox/com/defs.h"
179#include "VBox/com/ptr.h"
180#include "VBox/com/assert.h"
181#include "iprt/cpp/list.h"
182
183#ifdef VBOX_WITH_XPCOM
184
185/**
186 * Wraps the given com::SafeArray instance to generate an expression that is
187 * suitable for passing it to functions that take input safearray parameters
188 * declared using the ComSafeArrayIn macro.
189 *
190 * @param aArray com::SafeArray instance to pass as an input parameter.
191 */
192#define ComSafeArrayAsInParam(aArray) \
193 (aArray).size(), (aArray).__asInParam_Arr((aArray).raw())
194
195/**
196 * Wraps the given com::SafeArray instance to generate an expression that is
197 * suitable for passing it to functions that take output safearray parameters
198 * declared using the ComSafeArrayOut macro.
199 *
200 * @param aArray com::SafeArray instance to pass as an output parameter.
201 */
202#define ComSafeArrayAsOutParam(aArray) \
203 (aArray).__asOutParam_Size(), (aArray).__asOutParam_Arr()
204
205#else /* !VBOX_WITH_XPCOM */
206
207#define ComSafeArrayAsInParam(aArray) (aArray).__asInParam()
208
209#define ComSafeArrayAsOutParam(aArray) (aArray).__asOutParam()
210
211#endif /* !VBOX_WITH_XPCOM */
212
213/**
214 *
215 */
216namespace com
217{
218
219#ifdef VBOX_WITH_XPCOM
220
221////////////////////////////////////////////////////////////////////////////////
222
223/**
224 * Provides various helpers for SafeArray.
225 *
226 * @param T Type of array elements.
227 */
228template<typename T>
229struct SafeArrayTraits
230{
231protected:
232
233 /** Initializes memory for aElem. */
234 static void Init(T &aElem) { aElem = 0; }
235
236 /** Initializes memory occupied by aElem. */
237 static void Uninit(T &aElem) { aElem = 0; }
238
239 /** Creates a deep copy of aFrom and stores it in aTo. */
240 static void Copy(const T &aFrom, T &aTo) { aTo = aFrom; }
241
242public:
243
244 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard (that
245 * in particular forbid casts of 'char **' to 'const char **'). Then initial
246 * reason for this magic is that XPIDL declares input strings
247 * (char/PRUnichar pointers) as const but doesn't do so for pointers to
248 * arrays. */
249 static T *__asInParam_Arr(T *aArr) { return aArr; }
250 static T *__asInParam_Arr(const T *aArr) { return const_cast<T *>(aArr); }
251};
252
253template<typename T>
254struct SafeArrayTraits<T *>
255{
256 // Arbitrary pointers are not supported
257};
258
259template<>
260struct SafeArrayTraits<PRUnichar *>
261{
262protected:
263
264 static void Init(PRUnichar * &aElem) { aElem = NULL; }
265
266 static void Uninit(PRUnichar * &aElem)
267 {
268 if (aElem)
269 {
270 ::SysFreeString(aElem);
271 aElem = NULL;
272 }
273 }
274
275 static void Copy(const PRUnichar * aFrom, PRUnichar * &aTo)
276 {
277 AssertCompile(sizeof(PRUnichar) == sizeof(OLECHAR));
278 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
279 }
280
281public:
282
283 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
284 static const PRUnichar **__asInParam_Arr(PRUnichar **aArr)
285 {
286 return const_cast<const PRUnichar **>(aArr);
287 }
288 static const PRUnichar **__asInParam_Arr(const PRUnichar **aArr) { return aArr; }
289};
290
291template<>
292struct SafeArrayTraits<const PRUnichar *>
293{
294protected:
295
296 static void Init(const PRUnichar * &aElem) { aElem = NULL; }
297 static void Uninit(const PRUnichar * &aElem)
298 {
299 if (aElem)
300 {
301 ::SysFreeString(const_cast<PRUnichar *>(aElem));
302 aElem = NULL;
303 }
304 }
305
306 static void Copy(const PRUnichar * aFrom, const PRUnichar * &aTo)
307 {
308 AssertCompile(sizeof(PRUnichar) == sizeof(OLECHAR));
309 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
310 }
311
312public:
313
314 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
315 static const PRUnichar **__asInParam_Arr(const PRUnichar **aArr) { return aArr; }
316};
317
318template<>
319struct SafeArrayTraits<nsID *>
320{
321protected:
322
323 static void Init(nsID * &aElem) { aElem = NULL; }
324
325 static void Uninit(nsID * &aElem)
326 {
327 if (aElem)
328 {
329 ::nsMemory::Free(aElem);
330 aElem = NULL;
331 }
332 }
333
334 static void Copy(const nsID * aFrom, nsID * &aTo)
335 {
336 if (aFrom)
337 {
338 aTo = (nsID *) ::nsMemory::Alloc(sizeof(nsID));
339 if (aTo)
340 *aTo = *aFrom;
341 }
342 else
343 aTo = NULL;
344 }
345
346 /* This specification is also reused for SafeConstGUIDArray, so provide a
347 * no-op Init() and Uninit() which are necessary for SafeArray<> but should
348 * be never called in context of SafeConstGUIDArray. */
349
350 static void Init(const nsID * &aElem) { NOREF(aElem); AssertFailed(); }
351 static void Uninit(const nsID * &aElem) { NOREF(aElem); AssertFailed(); }
352
353public:
354
355 /** Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
356 static const nsID **__asInParam_Arr(nsID **aArr)
357 {
358 return const_cast<const nsID **>(aArr);
359 }
360 static const nsID **__asInParam_Arr(const nsID **aArr) { return aArr; }
361};
362
363#else /* !VBOX_WITH_XPCOM */
364
365////////////////////////////////////////////////////////////////////////////////
366
367struct SafeArrayTraitsBase
368{
369protected:
370
371 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
372 { return SafeArrayCreate(aVarType, 1, aBound); }
373};
374
375/**
376 * Provides various helpers for SafeArray.
377 *
378 * @param T Type of array elements.
379 *
380 * Specializations of this template must provide the following methods:
381 *
382 // Returns the VARTYPE of COM SafeArray elements to be used for T
383 static VARTYPE VarType();
384
385 // Returns the number of VarType() elements necessary for aSize
386 // elements of T
387 static ULONG VarCount(size_t aSize);
388
389 // Returns the number of elements of T that fit into the given number of
390 // VarType() elements (opposite to VarCount(size_t aSize)).
391 static size_t Size(ULONG aVarCount);
392
393 // Creates a deep copy of aFrom and stores it in aTo
394 static void Copy(ULONG aFrom, ULONG &aTo);
395 */
396template<typename T>
397struct SafeArrayTraits : public SafeArrayTraitsBase
398{
399protected:
400
401 // Arbitrary types are treated as passed by value and each value is
402 // represented by a number of VT_Ix type elements where VT_Ix has the
403 // biggest possible bitness necessary to represent T w/o a gap. COM enums
404 // fall into this category.
405
406 static VARTYPE VarType()
407 {
408#ifdef VBOX_WITH_TYPE_TRAITS
409 if ( std::is_integral<T>::value
410 && !std::is_signed<T>::value)
411 {
412 if (sizeof(T) % 8 == 0) return VT_UI8;
413 if (sizeof(T) % 4 == 0) return VT_UI4;
414 if (sizeof(T) % 2 == 0) return VT_UI2;
415 return VT_UI1;
416 }
417#endif
418 if (sizeof(T) % 8 == 0) return VT_I8;
419 if (sizeof(T) % 4 == 0) return VT_I4;
420 if (sizeof(T) % 2 == 0) return VT_I2;
421 return VT_I1;
422 }
423
424 /*
425 * Fallback method in case type traits (VBOX_WITH_TYPE_TRAITS)
426 * are not available. Always returns unsigned types.
427 */
428 static VARTYPE VarTypeUnsigned()
429 {
430 if (sizeof(T) % 8 == 0) return VT_UI8;
431 if (sizeof(T) % 4 == 0) return VT_UI4;
432 if (sizeof(T) % 2 == 0) return VT_UI2;
433 return VT_UI1;
434 }
435
436 static ULONG VarCount(size_t aSize)
437 {
438 if (sizeof(T) % 8 == 0) return (ULONG)((sizeof(T) / 8) * aSize);
439 if (sizeof(T) % 4 == 0) return (ULONG)((sizeof(T) / 4) * aSize);
440 if (sizeof(T) % 2 == 0) return (ULONG)((sizeof(T) / 2) * aSize);
441 return (ULONG)(sizeof(T) * aSize);
442 }
443
444 static size_t Size(ULONG aVarCount)
445 {
446 if (sizeof(T) % 8 == 0) return (size_t)(aVarCount * 8) / sizeof(T);
447 if (sizeof(T) % 4 == 0) return (size_t)(aVarCount * 4) / sizeof(T);
448 if (sizeof(T) % 2 == 0) return (size_t)(aVarCount * 2) / sizeof(T);
449 return (size_t) aVarCount / sizeof(T);
450 }
451
452 static void Copy(T aFrom, T &aTo) { aTo = aFrom; }
453};
454
455template<typename T>
456struct SafeArrayTraits<T *>
457{
458 // Arbitrary pointer types are not supported
459};
460
461/* Although the generic SafeArrayTraits template would work for all integers,
462 * we specialize it for some of them in order to use the correct VT_ type */
463
464template<>
465struct SafeArrayTraits<LONG> : public SafeArrayTraitsBase
466{
467protected:
468
469 static VARTYPE VarType() { return VT_I4; }
470 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
471 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
472
473 static void Copy(LONG aFrom, LONG &aTo) { aTo = aFrom; }
474};
475
476template<>
477struct SafeArrayTraits<ULONG> : public SafeArrayTraitsBase
478{
479protected:
480
481 static VARTYPE VarType() { return VT_UI4; }
482 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
483 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
484
485 static void Copy(ULONG aFrom, ULONG &aTo) { aTo = aFrom; }
486};
487
488template<>
489struct SafeArrayTraits<LONG64> : public SafeArrayTraitsBase
490{
491protected:
492
493 static VARTYPE VarType() { return VT_I8; }
494 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
495 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
496
497 static void Copy(LONG64 aFrom, LONG64 &aTo) { aTo = aFrom; }
498};
499
500template<>
501struct SafeArrayTraits<ULONG64> : public SafeArrayTraitsBase
502{
503protected:
504
505 static VARTYPE VarType() { return VT_UI8; }
506 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
507 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
508
509 static void Copy(ULONG64 aFrom, ULONG64 &aTo) { aTo = aFrom; }
510};
511
512template<>
513struct SafeArrayTraits<BSTR> : public SafeArrayTraitsBase
514{
515protected:
516
517 static VARTYPE VarType() { return VT_BSTR; }
518 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
519 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
520
521 static void Copy(BSTR aFrom, BSTR &aTo)
522 {
523 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
524 }
525};
526
527template<>
528struct SafeArrayTraits<GUID> : public SafeArrayTraitsBase
529{
530protected:
531
532 /* Use the 64-bit unsigned integer type for GUID */
533 static VARTYPE VarType() { return VT_UI8; }
534
535 /* GUID is 128 bit, so we need two VT_UI8 */
536 static ULONG VarCount(size_t aSize)
537 {
538 AssertCompileSize(GUID, 16);
539 return (ULONG)(aSize * 2);
540 }
541
542 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount / 2; }
543
544 static void Copy(GUID aFrom, GUID &aTo) { aTo = aFrom; }
545};
546
547/**
548 * Helper for SafeArray::__asOutParam() that automatically updates m.raw after a
549 * non-NULL m.arr assignment.
550 */
551class OutSafeArrayDipper
552{
553 OutSafeArrayDipper(SAFEARRAY **aArr, void **aRaw)
554 : arr(aArr), raw(aRaw) { Assert(*aArr == NULL && *aRaw == NULL); }
555
556 SAFEARRAY **arr;
557 void **raw;
558
559 template<class, class> friend class SafeArray;
560
561public:
562
563 ~OutSafeArrayDipper()
564 {
565 if (*arr != NULL)
566 {
567 HRESULT rc = SafeArrayAccessData(*arr, raw);
568 AssertComRC(rc);
569 }
570 }
571
572 operator SAFEARRAY **() { return arr; }
573};
574
575#endif /* !VBOX_WITH_XPCOM */
576
577////////////////////////////////////////////////////////////////////////////////
578
579/**
580 * The SafeArray class represents the safe array type used in COM to pass arrays
581 * to/from interface methods.
582 *
583 * This helper class hides all MSCOM/XPCOM specific implementation details and,
584 * together with ComSafeArrayIn, ComSafeArrayOut and ComSafeArrayRet macros,
585 * provides a platform-neutral way to handle safe arrays in the method
586 * implementation.
587 *
588 * When an instance of this class is destroyed, it automatically frees all
589 * resources occupied by individual elements of the array as well as by the
590 * array itself. However, when the value of an element is manually changed
591 * using #operator[] or by accessing array data through the #raw() pointer, it is
592 * the caller's responsibility to free resources occupied by the previous
593 * element's value.
594 *
595 * Also, objects of this class do not support copy and assignment operations and
596 * therefore cannot be returned from functions by value. In other words, this
597 * class is just a temporary storage for handling interface method calls and not
598 * intended to be used to store arrays as data members and such -- you should
599 * use normal list/vector classes for that.
600 *
601 * @note The current implementation supports only one-dimensional arrays.
602 *
603 * @note This class is not thread-safe.
604 */
605template<typename T, class Traits = SafeArrayTraits<T> >
606class SafeArray : public Traits
607{
608public:
609
610 /**
611 * Creates a null array.
612 */
613 SafeArray() {}
614
615 /**
616 * Creates a new array of the given size. All elements of the newly created
617 * array initialized with null values.
618 *
619 * @param aSize Initial number of elements in the array.
620 *
621 * @note If this object remains null after construction it means that there
622 * was not enough memory for creating an array of the requested size.
623 * The constructor will also assert in this case.
624 */
625 SafeArray(size_t aSize) { resize(aSize); }
626
627 /**
628 * Weakly attaches this instance to the existing array passed in a method
629 * parameter declared using the ComSafeArrayIn macro. When using this call,
630 * always wrap the parameter name in the ComSafeArrayInArg macro call like
631 * this:
632 * <pre>
633 * SafeArray safeArray(ComSafeArrayInArg(aArg));
634 * </pre>
635 *
636 * Note that this constructor doesn't take the ownership of the array. In
637 * particular, it means that operations that operate on the ownership (e.g.
638 * #detachTo()) are forbidden and will assert.
639 *
640 * @param aArg Input method parameter to attach to.
641 */
642 SafeArray(ComSafeArrayIn(T, aArg))
643 {
644#ifdef VBOX_WITH_XPCOM
645
646 AssertReturnVoid(aArg != NULL);
647
648 m.size = aArgSize;
649 m.arr = aArg;
650 m.isWeak = true;
651
652#else /* !VBOX_WITH_XPCOM */
653
654 AssertReturnVoid(aArg != NULL);
655 SAFEARRAY *arg = aArg;
656
657 if (arg)
658 {
659 AssertReturnVoid(arg->cDims == 1);
660
661 VARTYPE vt;
662 HRESULT rc = SafeArrayGetVartype(arg, &vt);
663 AssertComRCReturnVoid(rc);
664# ifndef VBOX_WITH_TYPE_TRAITS
665 AssertMsgReturnVoid(
666 vt == VarType()
667 || vt == VarTypeUnsigned(),
668 ("Expected vartype %d or %d, got %d.\n",
669 VarType(), VarTypeUnsigned(), vt));
670# else /* !VBOX_WITH_TYPE_TRAITS */
671 AssertMsgReturnVoid(
672 vt == VarType(),
673 ("Expected vartype %d, got %d.\n",
674 VarType(), vt));
675# endif
676 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
677 AssertComRCReturnVoid(rc);
678 }
679
680 m.arr = arg;
681 m.isWeak = true;
682
683#endif /* !VBOX_WITH_XPCOM */
684 }
685
686 /**
687 * Creates a deep copy of the given standard C++ container that stores
688 * T objects.
689 *
690 * @param aCntr Container object to copy.
691 *
692 * @param C Standard C++ container template class (normally deduced from
693 * @c aCntr).
694 */
695 template<template<typename, typename> class C, class A>
696 SafeArray(const C<T, A> & aCntr)
697 {
698 resize(aCntr.size());
699 AssertReturnVoid(!isNull());
700
701 size_t i = 0;
702 for (typename C<T, A>::const_iterator it = aCntr.begin();
703 it != aCntr.end(); ++ it, ++ i)
704#ifdef VBOX_WITH_XPCOM
705 SafeArray::Copy(*it, m.arr[i]);
706#else
707 Copy(*it, m.raw[i]);
708#endif
709 }
710
711 /**
712 * Creates a deep copy of the given standard C++ map that stores T objects
713 * as values.
714 *
715 * @param aMap Map object to copy.
716 *
717 * @param C Standard C++ map template class (normally deduced from
718 * @c aCntr).
719 * @param L Standard C++ compare class (deduced from @c aCntr).
720 * @param A Standard C++ allocator class (deduced from @c aCntr).
721 * @param K Map key class (deduced from @c aCntr).
722 */
723 template<template<typename, typename, typename, typename>
724 class C, class L, class A, class K>
725 SafeArray(const C<K, T, L, A> & aMap)
726 {
727 typedef C<K, T, L, A> Map;
728
729 resize(aMap.size());
730 AssertReturnVoid(!isNull());
731
732 int i = 0;
733 for (typename Map::const_iterator it = aMap.begin();
734 it != aMap.end(); ++ it, ++ i)
735#ifdef VBOX_WITH_XPCOM
736 Copy(it->second, m.arr[i]);
737#else
738 Copy(it->second, m.raw[i]);
739#endif
740 }
741
742 /**
743 * Destroys this instance after calling #setNull() to release allocated
744 * resources. See #setNull() for more details.
745 */
746 virtual ~SafeArray() { setNull(); }
747
748 /**
749 * Returns @c true if this instance represents a null array.
750 */
751 bool isNull() const { return m.arr == NULL; }
752
753 /**
754 * Returns @c true if this instance does not represents a null array.
755 */
756 bool isNotNull() const { return m.arr != NULL; }
757
758 /**
759 * Resets this instance to null and, if this instance is not a weak one,
760 * releases any resources occupied by the array data.
761 *
762 * @note This method destroys (cleans up) all elements of the array using
763 * the corresponding cleanup routine for the element type before the
764 * array itself is destroyed.
765 */
766 virtual void setNull() { m.uninit(); }
767
768 /**
769 * Returns @c true if this instance is weak. A weak instance doesn't own the
770 * array data and therefore operations manipulating the ownership (e.g.
771 * #detachTo()) are forbidden and will assert.
772 */
773 bool isWeak() const { return m.isWeak; }
774
775 /** Number of elements in the array. */
776 size_t size() const
777 {
778#ifdef VBOX_WITH_XPCOM
779 if (m.arr)
780 return m.size;
781 return 0;
782#else
783 if (m.arr)
784 return Size(m.arr->rgsabound[0].cElements);
785 return 0;
786#endif
787 }
788
789 /**
790 * Appends a copy of the given element at the end of the array.
791 *
792 * The array size is increased by one by this method and the additional
793 * space is allocated as needed.
794 *
795 * This method is handy in cases where you want to assign a copy of the
796 * existing value to the array element, for example:
797 * <tt>Bstr string; array.push_back(string);</tt>. If you create a string
798 * just to put it in the array, you may find #appendedRaw() more useful.
799 *
800 * @param aElement Element to append.
801 *
802 * @return @c true on success and @c false if there is not enough
803 * memory for resizing.
804 */
805 bool push_back(const T &aElement)
806 {
807 if (!ensureCapacity(size() + 1))
808 return false;
809
810#ifdef VBOX_WITH_XPCOM
811 SafeArray::Copy(aElement, m.arr[m.size]);
812 ++ m.size;
813#else
814 Copy(aElement, m.raw[size() - 1]);
815#endif
816 return true;
817 }
818
819 /**
820 * Appends an empty element at the end of the array and returns a raw
821 * pointer to it suitable for assigning a raw value (w/o constructing a
822 * copy).
823 *
824 * The array size is increased by one by this method and the additional
825 * space is allocated as needed.
826 *
827 * Note that in case of raw assignment, value ownership (for types with
828 * dynamically allocated data and for interface pointers) is transferred to
829 * the safe array object.
830 *
831 * This method is handy for operations like
832 * <tt>Bstr("foo").detachTo(array.appendedRaw());</tt>. Don't use it as
833 * an l-value (<tt>array.appendedRaw() = SysAllocString(L"tralala");</tt>)
834 * since this doesn't check for a NULL condition; use #resize() and
835 * #setRawAt() instead. If you need to assign a copy of the existing value
836 * instead of transferring the ownership, look at #push_back().
837 *
838 * @return Raw pointer to the added element or NULL if no memory.
839 */
840 T *appendedRaw()
841 {
842 if (!ensureCapacity(size() + 1))
843 return NULL;
844
845#ifdef VBOX_WITH_XPCOM
846 SafeArray::Init(m.arr[m.size]);
847 ++ m.size;
848 return &m.arr[m.size - 1];
849#else
850 /* nothing to do here, SafeArrayCreate() has performed element
851 * initialization */
852 return &m.raw[size() - 1];
853#endif
854 }
855
856 /**
857 * Resizes the array preserving its contents when possible. If the new size
858 * is larger than the old size, new elements are initialized with null
859 * values. If the new size is less than the old size, the contents of the
860 * array beyond the new size is lost.
861 *
862 * @param aNewSize New number of elements in the array.
863 * @return @c true on success and @c false if there is not enough
864 * memory for resizing.
865 */
866 bool resize(size_t aNewSize)
867 {
868 if (!ensureCapacity(aNewSize))
869 return false;
870
871#ifdef VBOX_WITH_XPCOM
872
873 if (m.size < aNewSize)
874 {
875 /* initialize the new elements */
876 for (size_t i = m.size; i < aNewSize; ++ i)
877 SafeArray::Init(m.arr[i]);
878 }
879
880 m.size = aNewSize;
881#else
882 /* nothing to do here, SafeArrayCreate() has performed element
883 * initialization */
884#endif
885 return true;
886 }
887
888 /**
889 * Reinitializes this instance by preallocating space for the given number
890 * of elements. The previous array contents is lost.
891 *
892 * @param aNewSize New number of elements in the array.
893 * @return @c true on success and @c false if there is not enough
894 * memory for resizing.
895 */
896 bool reset(size_t aNewSize)
897 {
898 m.uninit();
899 return resize(aNewSize);
900 }
901
902 /**
903 * Returns a pointer to the raw array data. Use this raw pointer with care
904 * as no type or bound checking is done for you in this case.
905 *
906 * @note This method returns @c NULL when this instance is null.
907 * @see #operator[]
908 */
909 T *raw()
910 {
911#ifdef VBOX_WITH_XPCOM
912 return m.arr;
913#else
914 return m.raw;
915#endif
916 }
917
918 /**
919 * Const version of #raw().
920 */
921 const T *raw() const
922 {
923#ifdef VBOX_WITH_XPCOM
924 return m.arr;
925#else
926 return m.raw;
927#endif
928 }
929
930 /**
931 * Array access operator that returns an array element by reference. A bit
932 * safer than #raw(): asserts and returns an invalid reference if this
933 * instance is null or if the index is out of bounds.
934 *
935 * @note For weak instances, this call will succeed but the behavior of
936 * changing the contents of an element of the weak array instance is
937 * undefined and may lead to a program crash on some platforms.
938 */
939 T &operator[] (size_t aIdx)
940 {
941 AssertReturn(m.arr != NULL, *((T *)NULL));
942 AssertReturn(aIdx < size(), *((T *)NULL));
943#ifdef VBOX_WITH_XPCOM
944 return m.arr[aIdx];
945#else
946 AssertReturn(m.raw != NULL, *((T *)NULL));
947 return m.raw[aIdx];
948#endif
949 }
950
951 /**
952 * Const version of #operator[] that returns an array element by value.
953 */
954 const T operator[] (size_t aIdx) const
955 {
956 AssertReturn(m.arr != NULL, *((T *)NULL));
957 AssertReturn(aIdx < size(), *((T *)NULL));
958#ifdef VBOX_WITH_XPCOM
959 return m.arr[aIdx];
960#else
961 AssertReturn(m.raw != NULL, *((T *)NULL));
962 return m.raw[aIdx];
963#endif
964 }
965
966 /**
967 * Creates a copy of this array and stores it in a method parameter declared
968 * using the ComSafeArrayOut macro. When using this call, always wrap the
969 * parameter name in the ComSafeArrayOutArg macro call like this:
970 * <pre>
971 * safeArray.cloneTo(ComSafeArrayOutArg(aArg));
972 * </pre>
973 *
974 * @note It is assumed that the ownership of the returned copy is
975 * transferred to the caller of the method and he is responsible to free the
976 * array data when it is no longer needed.
977 *
978 * @param aArg Output method parameter to clone to.
979 */
980 virtual const SafeArray &cloneTo(ComSafeArrayOut(T, aArg)) const
981 {
982 /// @todo Implement me!
983#ifdef VBOX_WITH_XPCOM
984 NOREF(aArgSize);
985 NOREF(aArg);
986#else
987 NOREF(aArg);
988#endif
989 AssertFailedReturn(*this);
990 }
991
992 void cloneTo(SafeArray<T>& aOther) const
993 {
994 aOther.reset(size());
995 aOther.initFrom(*this);
996 }
997
998
999 /**
1000 * Transfers the ownership of this array's data to the specified location
1001 * declared using the ComSafeArrayOut macro and makes this array a null
1002 * array. When using this call, always wrap the parameter name in the
1003 * ComSafeArrayOutArg macro call like this:
1004 * <pre>
1005 * safeArray.detachTo(ComSafeArrayOutArg(aArg));
1006 * </pre>
1007 *
1008 * Detaching the null array is also possible in which case the location will
1009 * receive NULL.
1010 *
1011 * @note Since the ownership of the array data is transferred to the
1012 * caller of the method, he is responsible to free the array data when it is
1013 * no longer needed.
1014 *
1015 * @param aArg Location to detach to.
1016 */
1017 virtual SafeArray &detachTo(ComSafeArrayOut(T, aArg))
1018 {
1019 AssertReturn(m.isWeak == false, *this);
1020
1021#ifdef VBOX_WITH_XPCOM
1022
1023 AssertReturn(aArgSize != NULL, *this);
1024 AssertReturn(aArg != NULL, *this);
1025
1026 *aArgSize = m.size;
1027 *aArg = m.arr;
1028
1029 m.isWeak = false;
1030 m.size = 0;
1031 m.arr = NULL;
1032
1033#else /* !VBOX_WITH_XPCOM */
1034
1035 AssertReturn(aArg != NULL, *this);
1036 *aArg = m.arr;
1037
1038 if (m.raw)
1039 {
1040 HRESULT rc = SafeArrayUnaccessData(m.arr);
1041 AssertComRCReturn(rc, *this);
1042 m.raw = NULL;
1043 }
1044
1045 m.isWeak = false;
1046 m.arr = NULL;
1047
1048#endif /* !VBOX_WITH_XPCOM */
1049
1050 return *this;
1051 }
1052
1053 /**
1054 * Returns a copy of this SafeArray as RTCList<T>.
1055 */
1056 RTCList<T> toList()
1057 {
1058 RTCList<T> list(size());
1059 for (size_t i = 0; i < size(); ++i)
1060#ifdef VBOX_WITH_XPCOM
1061 list.append(m.arr[i]);
1062#else
1063 list.append(m.raw[i]);
1064#endif
1065 return list;
1066 }
1067
1068 inline void initFrom(const com::SafeArray<T> & aRef);
1069 inline void initFrom(const T* aPtr, size_t aSize);
1070
1071 // Public methods for internal purposes only.
1072
1073#ifdef VBOX_WITH_XPCOM
1074
1075 /** Internal function. Never call it directly. */
1076 PRUint32 *__asOutParam_Size() { setNull(); return &m.size; }
1077
1078 /** Internal function Never call it directly. */
1079 T **__asOutParam_Arr() { Assert(isNull()); return &m.arr; }
1080
1081#else /* !VBOX_WITH_XPCOM */
1082
1083 /** Internal function Never call it directly. */
1084 SAFEARRAY * __asInParam() { return m.arr; }
1085
1086 /** Internal function Never call it directly. */
1087 OutSafeArrayDipper __asOutParam()
1088 { setNull(); return OutSafeArrayDipper(&m.arr, (void **)&m.raw); }
1089
1090#endif /* !VBOX_WITH_XPCOM */
1091
1092 static const SafeArray Null;
1093
1094protected:
1095
1096 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(SafeArray)
1097
1098 /**
1099 * Ensures that the array is big enough to contain aNewSize elements.
1100 *
1101 * If the new size is greater than the current capacity, a new array is
1102 * allocated and elements from the old array are copied over. The size of
1103 * the array doesn't change, only the capacity increases (which is always
1104 * greater than the size). Note that the additionally allocated elements are
1105 * left uninitialized by this method.
1106 *
1107 * If the new size is less than the current size, the existing array is
1108 * truncated to the specified size and the elements outside the new array
1109 * boundary are freed.
1110 *
1111 * If the new size is the same as the current size, nothing happens.
1112 *
1113 * @param aNewSize New size of the array.
1114 *
1115 * @return @c true on success and @c false if not enough memory.
1116 */
1117 bool ensureCapacity(size_t aNewSize)
1118 {
1119 AssertReturn(!m.isWeak, false);
1120
1121#ifdef VBOX_WITH_XPCOM
1122
1123 /* Note: we distinguish between a null array and an empty (zero
1124 * elements) array. Therefore we never use zero in malloc (even if
1125 * aNewSize is zero) to make sure we get a non-null pointer. */
1126
1127 if (m.size == aNewSize && m.arr != NULL)
1128 return true;
1129
1130 /* Allocate in 16-byte pieces. */
1131 size_t newCapacity = RT_MAX((aNewSize + 15) / 16 * 16, 16);
1132
1133 if (m.capacity != newCapacity)
1134 {
1135 T *newArr = (T *)nsMemory::Alloc(RT_MAX(newCapacity, 1) * sizeof(T));
1136 AssertReturn(newArr != NULL, false);
1137
1138 if (m.arr != NULL)
1139 {
1140 if (m.size > aNewSize)
1141 {
1142 /* Truncation takes place, uninit exceeding elements and
1143 * shrink the size. */
1144 for (size_t i = aNewSize; i < m.size; ++ i)
1145 SafeArray::Uninit(m.arr[i]);
1146
1147 m.size = aNewSize;
1148 }
1149
1150 /* Copy the old contents. */
1151 memcpy(newArr, m.arr, m.size * sizeof(T));
1152 nsMemory::Free((void *)m.arr);
1153 }
1154
1155 m.arr = newArr;
1156 }
1157 else
1158 {
1159 if (m.size > aNewSize)
1160 {
1161 /* Truncation takes place, uninit exceeding elements and
1162 * shrink the size. */
1163 for (size_t i = aNewSize; i < m.size; ++ i)
1164 SafeArray::Uninit(m.arr[i]);
1165
1166 m.size = aNewSize;
1167 }
1168 }
1169
1170 m.capacity = newCapacity;
1171
1172#else
1173
1174 SAFEARRAYBOUND bound = { VarCount(aNewSize), 0 };
1175 HRESULT rc;
1176
1177 if (m.arr == NULL)
1178 {
1179 m.arr = CreateSafeArray(VarType(), &bound);
1180 AssertReturn(m.arr != NULL, false);
1181 }
1182 else
1183 {
1184 SafeArrayUnaccessData(m.arr);
1185
1186 rc = SafeArrayRedim(m.arr, &bound);
1187 AssertComRCReturn(rc == S_OK, false);
1188 }
1189
1190 rc = SafeArrayAccessData(m.arr, (void HUGEP **)&m.raw);
1191 AssertComRCReturn(rc, false);
1192
1193#endif
1194 return true;
1195 }
1196
1197 struct Data
1198 {
1199 Data()
1200 : isWeak(false)
1201#ifdef VBOX_WITH_XPCOM
1202 , capacity(0), size(0), arr(NULL)
1203#else
1204 , arr(NULL), raw(NULL)
1205#endif
1206 {}
1207
1208 ~Data() { uninit(); }
1209
1210 void uninit()
1211 {
1212#ifdef VBOX_WITH_XPCOM
1213
1214 if (arr)
1215 {
1216 if (!isWeak)
1217 {
1218 for (size_t i = 0; i < size; ++ i)
1219 SafeArray::Uninit(arr[i]);
1220
1221 nsMemory::Free((void *)arr);
1222 }
1223 else
1224 isWeak = false;
1225
1226 arr = NULL;
1227 }
1228
1229 size = capacity = 0;
1230
1231#else /* !VBOX_WITH_XPCOM */
1232
1233 if (arr)
1234 {
1235 if (raw)
1236 {
1237 SafeArrayUnaccessData(arr);
1238 raw = NULL;
1239 }
1240
1241 if (!isWeak)
1242 {
1243 HRESULT rc = SafeArrayDestroy(arr);
1244 AssertComRCReturnVoid(rc);
1245 }
1246 else
1247 isWeak = false;
1248
1249 arr = NULL;
1250 }
1251
1252#endif /* !VBOX_WITH_XPCOM */
1253 }
1254
1255 bool isWeak : 1;
1256
1257#ifdef VBOX_WITH_XPCOM
1258 PRUint32 capacity;
1259 PRUint32 size;
1260 T *arr;
1261#else
1262 SAFEARRAY *arr;
1263 T *raw;
1264#endif
1265 };
1266
1267 Data m;
1268};
1269
1270/* Few fast specializations for primitive array types */
1271template<>
1272inline void com::SafeArray<BYTE>::initFrom(const com::SafeArray<BYTE> & aRef)
1273{
1274 size_t sSize = aRef.size();
1275 resize(sSize);
1276 ::memcpy(raw(), aRef.raw(), sSize);
1277}
1278template<>
1279inline void com::SafeArray<BYTE>::initFrom(const BYTE* aPtr, size_t aSize)
1280{
1281 resize(aSize);
1282 ::memcpy(raw(), aPtr, aSize);
1283}
1284
1285
1286template<>
1287inline void com::SafeArray<SHORT>::initFrom(const com::SafeArray<SHORT> & aRef)
1288{
1289 size_t sSize = aRef.size();
1290 resize(sSize);
1291 ::memcpy(raw(), aRef.raw(), sSize * sizeof(SHORT));
1292}
1293template<>
1294inline void com::SafeArray<SHORT>::initFrom(const SHORT* aPtr, size_t aSize)
1295{
1296 resize(aSize);
1297 ::memcpy(raw(), aPtr, aSize * sizeof(SHORT));
1298}
1299
1300template<>
1301inline void com::SafeArray<USHORT>::initFrom(const com::SafeArray<USHORT> & aRef)
1302{
1303 size_t sSize = aRef.size();
1304 resize(sSize);
1305 ::memcpy(raw(), aRef.raw(), sSize * sizeof(USHORT));
1306}
1307template<>
1308inline void com::SafeArray<USHORT>::initFrom(const USHORT* aPtr, size_t aSize)
1309{
1310 resize(aSize);
1311 ::memcpy(raw(), aPtr, aSize * sizeof(USHORT));
1312}
1313
1314template<>
1315inline void com::SafeArray<LONG>::initFrom(const com::SafeArray<LONG> & aRef)
1316{
1317 size_t sSize = aRef.size();
1318 resize(sSize);
1319 ::memcpy(raw(), aRef.raw(), sSize * sizeof(LONG));
1320}
1321template<>
1322inline void com::SafeArray<LONG>::initFrom(const LONG* aPtr, size_t aSize)
1323{
1324 resize(aSize);
1325 ::memcpy(raw(), aPtr, aSize * sizeof(LONG));
1326}
1327
1328
1329////////////////////////////////////////////////////////////////////////////////
1330
1331#ifdef VBOX_WITH_XPCOM
1332
1333/**
1334 * Version of com::SafeArray for arrays of GUID.
1335 *
1336 * In MS COM, GUID arrays store GUIDs by value and therefore input arrays are
1337 * represented using |GUID *| and out arrays -- using |GUID **|. In XPCOM,
1338 * GUID arrays store pointers to nsID so that input arrays are |const nsID **|
1339 * and out arrays are |nsID ***|. Due to this difference, it is impossible to
1340 * work with arrays of GUID on both platforms by simply using com::SafeArray
1341 * <GUID>. This class is intended to provide some level of cross-platform
1342 * behavior.
1343 *
1344 * The basic usage pattern is basically similar to com::SafeArray<> except that
1345 * you use ComSafeGUIDArrayIn* and ComSafeGUIDArrayOut* macros instead of
1346 * ComSafeArrayIn* and ComSafeArrayOut*. Another important nuance is that the
1347 * raw() array type is different (nsID **, or GUID ** on XPCOM and GUID * on MS
1348 * COM) so it is recommended to use operator[] instead which always returns a
1349 * GUID by value.
1350 *
1351 * Note that due to const modifiers, you cannot use SafeGUIDArray for input GUID
1352 * arrays. Please use SafeConstGUIDArray for this instead.
1353 *
1354 * Other than mentioned above, the functionality of this class is equivalent to
1355 * com::SafeArray<>. See the description of that template and its methods for
1356 * more information.
1357 *
1358 * Output GUID arrays are handled by a separate class, SafeGUIDArrayOut, since
1359 * this class cannot handle them because of const modifiers.
1360 */
1361class SafeGUIDArray : public SafeArray<nsID *>
1362{
1363public:
1364
1365 typedef SafeArray<nsID *> Base;
1366
1367 class nsIDRef
1368 {
1369 public:
1370
1371 nsIDRef(nsID * &aVal) : mVal(aVal) {}
1372
1373 operator const nsID &() const { return mVal ? *mVal : *Empty; }
1374 operator nsID() const { return mVal ? *mVal : *Empty; }
1375
1376 const nsID *operator&() const { return mVal ? mVal : Empty; }
1377
1378 nsIDRef &operator= (const nsID &aThat)
1379 {
1380 if (mVal == NULL)
1381 Copy(&aThat, mVal);
1382 else
1383 *mVal = aThat;
1384 return *this;
1385 }
1386
1387 private:
1388
1389 nsID * &mVal;
1390
1391 static const nsID *Empty;
1392
1393 friend class SafeGUIDArray;
1394 };
1395
1396 /** See SafeArray<>::SafeArray(). */
1397 SafeGUIDArray() {}
1398
1399 /** See SafeArray<>::SafeArray(size_t). */
1400 SafeGUIDArray(size_t aSize) : Base(aSize) {}
1401
1402 /**
1403 * Array access operator that returns an array element by reference. As a
1404 * special case, the return value of this operator on XPCOM is an nsID (GUID)
1405 * reference, instead of an nsID pointer (the actual SafeArray template
1406 * argument), for compatibility with the MS COM version.
1407 *
1408 * The rest is equivalent to SafeArray<>::operator[].
1409 */
1410 nsIDRef operator[] (size_t aIdx)
1411 {
1412 Assert(m.arr != NULL);
1413 Assert(aIdx < size());
1414 return nsIDRef(m.arr[aIdx]);
1415 }
1416
1417 /**
1418 * Const version of #operator[] that returns an array element by value.
1419 */
1420 const nsID &operator[] (size_t aIdx) const
1421 {
1422 Assert(m.arr != NULL);
1423 Assert(aIdx < size());
1424 return m.arr[aIdx] ? *m.arr[aIdx] : *nsIDRef::Empty;
1425 }
1426};
1427
1428/**
1429 * Version of com::SafeArray for const arrays of GUID.
1430 *
1431 * This class is used to work with input GUID array parameters in method
1432 * implementations. See SafeGUIDArray for more details.
1433 */
1434class SafeConstGUIDArray : public SafeArray<const nsID *,
1435 SafeArrayTraits<nsID *> >
1436{
1437public:
1438
1439 typedef SafeArray<const nsID *, SafeArrayTraits<nsID *> > Base;
1440
1441 /** See SafeArray<>::SafeArray(). */
1442 SafeConstGUIDArray() {}
1443
1444 /* See SafeArray<>::SafeArray(ComSafeArrayIn(T, aArg)). */
1445 SafeConstGUIDArray(ComSafeGUIDArrayIn(aArg))
1446 : Base(ComSafeGUIDArrayInArg(aArg)) {}
1447
1448 /**
1449 * Array access operator that returns an array element by reference. As a
1450 * special case, the return value of this operator on XPCOM is nsID (GUID)
1451 * instead of nsID *, for compatibility with the MS COM version.
1452 *
1453 * The rest is equivalent to SafeArray<>::operator[].
1454 */
1455 const nsID &operator[] (size_t aIdx) const
1456 {
1457 AssertReturn(m.arr != NULL, **((const nsID * *)NULL));
1458 AssertReturn(aIdx < size(), **((const nsID * *)NULL));
1459 return *m.arr[aIdx];
1460 }
1461
1462private:
1463
1464 /* These are disabled because of const. */
1465 bool reset(size_t aNewSize) { NOREF(aNewSize); return false; }
1466};
1467
1468#else /* !VBOX_WITH_XPCOM */
1469
1470typedef SafeArray<GUID> SafeGUIDArray;
1471typedef SafeArray<const GUID, SafeArrayTraits<GUID> > SafeConstGUIDArray;
1472
1473#endif /* !VBOX_WITH_XPCOM */
1474
1475////////////////////////////////////////////////////////////////////////////////
1476
1477#ifdef VBOX_WITH_XPCOM
1478
1479template<class I>
1480struct SafeIfaceArrayTraits
1481{
1482protected:
1483
1484 static void Init(I * &aElem) { aElem = NULL; }
1485 static void Uninit(I * &aElem)
1486 {
1487 if (aElem)
1488 {
1489 aElem->Release();
1490 aElem = NULL;
1491 }
1492 }
1493
1494 static void Copy(I * aFrom, I * &aTo)
1495 {
1496 if (aFrom != NULL)
1497 {
1498 aTo = aFrom;
1499 aTo->AddRef();
1500 }
1501 else
1502 aTo = NULL;
1503 }
1504
1505public:
1506
1507 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
1508 static I **__asInParam_Arr(I **aArr) { return aArr; }
1509 static I **__asInParam_Arr(const I **aArr) { return const_cast<I **>(aArr); }
1510};
1511
1512#else /* !VBOX_WITH_XPCOM */
1513
1514template<class I>
1515struct SafeIfaceArrayTraits
1516{
1517protected:
1518
1519 static VARTYPE VarType() { return VT_DISPATCH; }
1520 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
1521 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
1522
1523 static void Copy(I * aFrom, I * &aTo)
1524 {
1525 if (aFrom != NULL)
1526 {
1527 aTo = aFrom;
1528 aTo->AddRef();
1529 }
1530 else
1531 aTo = NULL;
1532 }
1533
1534 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
1535 {
1536 NOREF(aVarType);
1537 return SafeArrayCreateEx(VT_DISPATCH, 1, aBound, (PVOID)&_ATL_IIDOF(I));
1538 }
1539};
1540
1541#endif /* !VBOX_WITH_XPCOM */
1542
1543////////////////////////////////////////////////////////////////////////////////
1544
1545/**
1546 * Version of com::SafeArray for arrays of interface pointers.
1547 *
1548 * Except that it manages arrays of interface pointers, the usage of this class
1549 * is identical to com::SafeArray.
1550 *
1551 * @param I Interface class (no asterisk).
1552 */
1553template<class I>
1554class SafeIfaceArray : public SafeArray<I *, SafeIfaceArrayTraits<I> >
1555{
1556public:
1557
1558 typedef SafeArray<I *, SafeIfaceArrayTraits<I> > Base;
1559
1560 /**
1561 * Creates a null array.
1562 */
1563 SafeIfaceArray() {}
1564
1565 /**
1566 * Creates a new array of the given size. All elements of the newly created
1567 * array initialized with null values.
1568 *
1569 * @param aSize Initial number of elements in the array. Must be greater
1570 * than 0.
1571 *
1572 * @note If this object remains null after construction it means that there
1573 * was not enough memory for creating an array of the requested size.
1574 * The constructor will also assert in this case.
1575 */
1576 SafeIfaceArray(size_t aSize) { Base::resize(aSize); }
1577
1578 /**
1579 * Weakly attaches this instance to the existing array passed in a method
1580 * parameter declared using the ComSafeArrayIn macro. When using this call,
1581 * always wrap the parameter name in the ComSafeArrayOutArg macro call like
1582 * this:
1583 * <pre>
1584 * SafeArray safeArray(ComSafeArrayInArg(aArg));
1585 * </pre>
1586 *
1587 * Note that this constructor doesn't take the ownership of the array. In
1588 * particular, this means that operations that operate on the ownership
1589 * (e.g. #detachTo()) are forbidden and will assert.
1590 *
1591 * @param aArg Input method parameter to attach to.
1592 */
1593 SafeIfaceArray(ComSafeArrayIn(I *, aArg))
1594 {
1595#ifdef VBOX_WITH_XPCOM
1596
1597 AssertReturnVoid(aArg != NULL);
1598
1599 Base::m.size = aArgSize;
1600 Base::m.arr = aArg;
1601 Base::m.isWeak = true;
1602
1603#else /* !VBOX_WITH_XPCOM */
1604
1605 AssertReturnVoid(aArg != NULL);
1606 SAFEARRAY *arg = aArg;
1607
1608 if (arg)
1609 {
1610 AssertReturnVoid(arg->cDims == 1);
1611
1612 VARTYPE vt;
1613 HRESULT rc = SafeArrayGetVartype(arg, &vt);
1614 AssertComRCReturnVoid(rc);
1615 AssertMsgReturnVoid(vt == VT_UNKNOWN || vt == VT_DISPATCH,
1616 ("Expected vartype VT_UNKNOWN or VT_DISPATCH, got %d.\n",
1617 vt));
1618 GUID guid;
1619 rc = SafeArrayGetIID(arg, &guid);
1620 AssertComRCReturnVoid(rc);
1621 AssertMsgReturnVoid(InlineIsEqualGUID(_ATL_IIDOF(I), guid),
1622 ("Expected IID {%RTuuid}, got {%RTuuid}.\n",
1623 &_ATL_IIDOF(I), &guid));
1624
1625 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
1626 AssertComRCReturnVoid(rc);
1627 }
1628
1629 m.arr = arg;
1630 m.isWeak = true;
1631
1632#endif /* !VBOX_WITH_XPCOM */
1633 }
1634
1635 /**
1636 * Creates a deep copy of the given standard C++ container that stores
1637 * interface pointers as objects of the ComPtr<I> class.
1638 *
1639 * @param aCntr Container object to copy.
1640 *
1641 * @param C Standard C++ container template class (normally deduced from
1642 * @c aCntr).
1643 * @param A Standard C++ allocator class (deduced from @c aCntr).
1644 * @param OI Argument to the ComPtr template (deduced from @c aCntr).
1645 */
1646 template<template<typename, typename> class C, class A, class OI>
1647 SafeIfaceArray(const C<ComPtr<OI>, A> & aCntr)
1648 {
1649 typedef C<ComPtr<OI>, A> List;
1650
1651 Base::resize(aCntr.size());
1652 AssertReturnVoid(!Base::isNull());
1653
1654 int i = 0;
1655 for (typename List::const_iterator it = aCntr.begin();
1656 it != aCntr.end(); ++ it, ++ i)
1657#ifdef VBOX_WITH_XPCOM
1658 this->Copy(*it, Base::m.arr[i]);
1659#else
1660 Copy(*it, Base::m.raw[i]);
1661#endif
1662 }
1663
1664 /**
1665 * Creates a deep copy of the given standard C++ container that stores
1666 * interface pointers as objects of the ComObjPtr<I> class.
1667 *
1668 * @param aCntr Container object to copy.
1669 *
1670 * @param C Standard C++ container template class (normally deduced from
1671 * @c aCntr).
1672 * @param A Standard C++ allocator class (deduced from @c aCntr).
1673 * @param OI Argument to the ComObjPtr template (deduced from @c aCntr).
1674 */
1675 template<template<typename, typename> class C, class A, class OI>
1676 SafeIfaceArray(const C<ComObjPtr<OI>, A> & aCntr)
1677 {
1678 typedef C<ComObjPtr<OI>, A> List;
1679
1680 Base::resize(aCntr.size());
1681 AssertReturnVoid(!Base::isNull());
1682
1683 int i = 0;
1684 for (typename List::const_iterator it = aCntr.begin();
1685 it != aCntr.end(); ++ it, ++ i)
1686#ifdef VBOX_WITH_XPCOM
1687 SafeIfaceArray::Copy(*it, Base::m.arr[i]);
1688#else
1689 Copy(*it, Base::m.raw[i]);
1690#endif
1691 }
1692
1693 /**
1694 * Creates a deep copy of the given standard C++ map whose values are
1695 * interface pointers stored as objects of the ComPtr<I> class.
1696 *
1697 * @param aMap Map object to copy.
1698 *
1699 * @param C Standard C++ map template class (normally deduced from
1700 * @c aCntr).
1701 * @param L Standard C++ compare class (deduced from @c aCntr).
1702 * @param A Standard C++ allocator class (deduced from @c aCntr).
1703 * @param K Map key class (deduced from @c aCntr).
1704 * @param OI Argument to the ComPtr template (deduced from @c aCntr).
1705 */
1706 template<template<typename, typename, typename, typename>
1707 class C, class L, class A, class K, class OI>
1708 SafeIfaceArray(const C<K, ComPtr<OI>, L, A> & aMap)
1709 {
1710 typedef C<K, ComPtr<OI>, L, A> Map;
1711
1712 Base::resize(aMap.size());
1713 AssertReturnVoid(!Base::isNull());
1714
1715 int i = 0;
1716 for (typename Map::const_iterator it = aMap.begin();
1717 it != aMap.end(); ++ it, ++ i)
1718#ifdef VBOX_WITH_XPCOM
1719 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1720#else
1721 Copy(it->second, Base::m.raw[i]);
1722#endif
1723 }
1724
1725 /**
1726 * Creates a deep copy of the given standard C++ map whose values are
1727 * interface pointers stored as objects of the ComObjPtr<I> class.
1728 *
1729 * @param aMap Map object to copy.
1730 *
1731 * @param C Standard C++ map template class (normally deduced from
1732 * @c aCntr).
1733 * @param L Standard C++ compare class (deduced from @c aCntr).
1734 * @param A Standard C++ allocator class (deduced from @c aCntr).
1735 * @param K Map key class (deduced from @c aCntr).
1736 * @param OI Argument to the ComObjPtr template (deduced from @c aCntr).
1737 */
1738 template<template<typename, typename, typename, typename>
1739 class C, class L, class A, class K, class OI>
1740 SafeIfaceArray(const C<K, ComObjPtr<OI>, L, A> & aMap)
1741 {
1742 typedef C<K, ComObjPtr<OI>, L, A> Map;
1743
1744 Base::resize(aMap.size());
1745 AssertReturnVoid(!Base::isNull());
1746
1747 int i = 0;
1748 for (typename Map::const_iterator it = aMap.begin();
1749 it != aMap.end(); ++ it, ++ i)
1750#ifdef VBOX_WITH_XPCOM
1751 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1752#else
1753 Copy(it->second, Base::m.raw[i]);
1754#endif
1755 }
1756
1757 void setElement(size_t iIdx, I* obj)
1758 {
1759#ifdef VBOX_WITH_XPCOM
1760 SafeIfaceArray::Copy(obj, Base::m.arr[iIdx]);
1761#else
1762 Copy(obj, Base::m.raw[iIdx]);
1763#endif
1764 }
1765};
1766
1767} /* namespace com */
1768
1769/** @} */
1770
1771#endif /* !___VBox_com_array_h */
1772
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette