VirtualBox

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

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

Main: fix the remaining NULL safearray issues, the template had useless assertions and the helper code used by the wrappers also needed to check for it everywhere

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 51.2 KB
Line 
1/** @file
2 * MS COM / XPCOM Abstraction Layer - Safe array helper class declaration.
3 */
4
5/*
6 * Copyright (C) 2006-2014 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 if (aArg)
645 {
646#ifdef VBOX_WITH_XPCOM
647
648 m.size = aArgSize;
649 m.arr = aArg;
650 m.isWeak = true;
651
652#else /* !VBOX_WITH_XPCOM */
653
654 SAFEARRAY *arg = aArg;
655
656 AssertReturnVoid(arg->cDims == 1);
657
658 VARTYPE vt;
659 HRESULT rc = SafeArrayGetVartype(arg, &vt);
660 AssertComRCReturnVoid(rc);
661# ifndef VBOX_WITH_TYPE_TRAITS
662 AssertMsgReturnVoid(
663 vt == VarType()
664 || vt == VarTypeUnsigned(),
665 ("Expected vartype %d or %d, got %d.\n",
666 VarType(), VarTypeUnsigned(), vt));
667# else /* !VBOX_WITH_TYPE_TRAITS */
668 AssertMsgReturnVoid(
669 vt == VarType(),
670 ("Expected vartype %d, got %d.\n",
671 VarType(), vt));
672# endif
673 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
674 AssertComRCReturnVoid(rc);
675
676 m.arr = arg;
677 m.isWeak = true;
678
679#endif /* !VBOX_WITH_XPCOM */
680 }
681 }
682
683 /**
684 * Creates a deep copy of the given standard C++ container that stores
685 * T objects.
686 *
687 * @param aCntr Container object to copy.
688 *
689 * @param C Standard C++ container template class (normally deduced from
690 * @c aCntr).
691 */
692 template<template<typename, typename> class C, class A>
693 SafeArray(const C<T, A> & aCntr)
694 {
695 resize(aCntr.size());
696 AssertReturnVoid(!isNull());
697
698 size_t i = 0;
699 for (typename C<T, A>::const_iterator it = aCntr.begin();
700 it != aCntr.end(); ++ it, ++ i)
701#ifdef VBOX_WITH_XPCOM
702 SafeArray::Copy(*it, m.arr[i]);
703#else
704 Copy(*it, m.raw[i]);
705#endif
706 }
707
708 /**
709 * Creates a deep copy of the given standard C++ map that stores T objects
710 * as values.
711 *
712 * @param aMap Map object to copy.
713 *
714 * @param C Standard C++ map template class (normally deduced from
715 * @c aCntr).
716 * @param L Standard C++ compare class (deduced from @c aCntr).
717 * @param A Standard C++ allocator class (deduced from @c aCntr).
718 * @param K Map key class (deduced from @c aCntr).
719 */
720 template<template<typename, typename, typename, typename>
721 class C, class L, class A, class K>
722 SafeArray(const C<K, T, L, A> & aMap)
723 {
724 typedef C<K, T, L, A> Map;
725
726 resize(aMap.size());
727 AssertReturnVoid(!isNull());
728
729 int i = 0;
730 for (typename Map::const_iterator it = aMap.begin();
731 it != aMap.end(); ++ it, ++ i)
732#ifdef VBOX_WITH_XPCOM
733 Copy(it->second, m.arr[i]);
734#else
735 Copy(it->second, m.raw[i]);
736#endif
737 }
738
739 /**
740 * Destroys this instance after calling #setNull() to release allocated
741 * resources. See #setNull() for more details.
742 */
743 virtual ~SafeArray() { setNull(); }
744
745 /**
746 * Returns @c true if this instance represents a null array.
747 */
748 bool isNull() const { return m.arr == NULL; }
749
750 /**
751 * Returns @c true if this instance does not represents a null array.
752 */
753 bool isNotNull() const { return m.arr != NULL; }
754
755 /**
756 * Resets this instance to null and, if this instance is not a weak one,
757 * releases any resources occupied by the array data.
758 *
759 * @note This method destroys (cleans up) all elements of the array using
760 * the corresponding cleanup routine for the element type before the
761 * array itself is destroyed.
762 */
763 virtual void setNull() { m.uninit(); }
764
765 /**
766 * Returns @c true if this instance is weak. A weak instance doesn't own the
767 * array data and therefore operations manipulating the ownership (e.g.
768 * #detachTo()) are forbidden and will assert.
769 */
770 bool isWeak() const { return m.isWeak; }
771
772 /** Number of elements in the array. */
773 size_t size() const
774 {
775#ifdef VBOX_WITH_XPCOM
776 if (m.arr)
777 return m.size;
778 return 0;
779#else
780 if (m.arr)
781 return Size(m.arr->rgsabound[0].cElements);
782 return 0;
783#endif
784 }
785
786 /**
787 * Appends a copy of the given element at the end of the array.
788 *
789 * The array size is increased by one by this method and the additional
790 * space is allocated as needed.
791 *
792 * This method is handy in cases where you want to assign a copy of the
793 * existing value to the array element, for example:
794 * <tt>Bstr string; array.push_back(string);</tt>. If you create a string
795 * just to put it in the array, you may find #appendedRaw() more useful.
796 *
797 * @param aElement Element to append.
798 *
799 * @return @c true on success and @c false if there is not enough
800 * memory for resizing.
801 */
802 bool push_back(const T &aElement)
803 {
804 if (!ensureCapacity(size() + 1))
805 return false;
806
807#ifdef VBOX_WITH_XPCOM
808 SafeArray::Copy(aElement, m.arr[m.size]);
809 ++ m.size;
810#else
811 Copy(aElement, m.raw[size() - 1]);
812#endif
813 return true;
814 }
815
816 /**
817 * Appends an empty element at the end of the array and returns a raw
818 * pointer to it suitable for assigning a raw value (w/o constructing a
819 * copy).
820 *
821 * The array size is increased by one by this method and the additional
822 * space is allocated as needed.
823 *
824 * Note that in case of raw assignment, value ownership (for types with
825 * dynamically allocated data and for interface pointers) is transferred to
826 * the safe array object.
827 *
828 * This method is handy for operations like
829 * <tt>Bstr("foo").detachTo(array.appendedRaw());</tt>. Don't use it as
830 * an l-value (<tt>array.appendedRaw() = SysAllocString(L"tralala");</tt>)
831 * since this doesn't check for a NULL condition; use #resize() and
832 * #setRawAt() instead. If you need to assign a copy of the existing value
833 * instead of transferring the ownership, look at #push_back().
834 *
835 * @return Raw pointer to the added element or NULL if no memory.
836 */
837 T *appendedRaw()
838 {
839 if (!ensureCapacity(size() + 1))
840 return NULL;
841
842#ifdef VBOX_WITH_XPCOM
843 SafeArray::Init(m.arr[m.size]);
844 ++ m.size;
845 return &m.arr[m.size - 1];
846#else
847 /* nothing to do here, SafeArrayCreate() has performed element
848 * initialization */
849 return &m.raw[size() - 1];
850#endif
851 }
852
853 /**
854 * Resizes the array preserving its contents when possible. If the new size
855 * is larger than the old size, new elements are initialized with null
856 * values. If the new size is less than the old size, the contents of the
857 * array beyond the new size is lost.
858 *
859 * @param aNewSize New number of elements in the array.
860 * @return @c true on success and @c false if there is not enough
861 * memory for resizing.
862 */
863 bool resize(size_t aNewSize)
864 {
865 if (!ensureCapacity(aNewSize))
866 return false;
867
868#ifdef VBOX_WITH_XPCOM
869
870 if (m.size < aNewSize)
871 {
872 /* initialize the new elements */
873 for (size_t i = m.size; i < aNewSize; ++ i)
874 SafeArray::Init(m.arr[i]);
875 }
876
877 m.size = aNewSize;
878#else
879 /* nothing to do here, SafeArrayCreate() has performed element
880 * initialization */
881#endif
882 return true;
883 }
884
885 /**
886 * Reinitializes this instance by preallocating space for the given number
887 * of elements. The previous array contents is lost.
888 *
889 * @param aNewSize New number of elements in the array.
890 * @return @c true on success and @c false if there is not enough
891 * memory for resizing.
892 */
893 bool reset(size_t aNewSize)
894 {
895 m.uninit();
896 return resize(aNewSize);
897 }
898
899 /**
900 * Returns a pointer to the raw array data. Use this raw pointer with care
901 * as no type or bound checking is done for you in this case.
902 *
903 * @note This method returns @c NULL when this instance is null.
904 * @see #operator[]
905 */
906 T *raw()
907 {
908#ifdef VBOX_WITH_XPCOM
909 return m.arr;
910#else
911 return m.raw;
912#endif
913 }
914
915 /**
916 * Const version of #raw().
917 */
918 const T *raw() const
919 {
920#ifdef VBOX_WITH_XPCOM
921 return m.arr;
922#else
923 return m.raw;
924#endif
925 }
926
927 /**
928 * Array access operator that returns an array element by reference. A bit
929 * safer than #raw(): asserts and returns an invalid reference if this
930 * instance is null or if the index is out of bounds.
931 *
932 * @note For weak instances, this call will succeed but the behavior of
933 * changing the contents of an element of the weak array instance is
934 * undefined and may lead to a program crash on some platforms.
935 */
936 T &operator[] (size_t aIdx)
937 {
938 AssertReturn(m.arr != NULL, *((T *)NULL));
939 AssertReturn(aIdx < size(), *((T *)NULL));
940#ifdef VBOX_WITH_XPCOM
941 return m.arr[aIdx];
942#else
943 AssertReturn(m.raw != NULL, *((T *)NULL));
944 return m.raw[aIdx];
945#endif
946 }
947
948 /**
949 * Const version of #operator[] that returns an array element by value.
950 */
951 const T operator[] (size_t aIdx) const
952 {
953 AssertReturn(m.arr != NULL, *((T *)NULL));
954 AssertReturn(aIdx < size(), *((T *)NULL));
955#ifdef VBOX_WITH_XPCOM
956 return m.arr[aIdx];
957#else
958 AssertReturn(m.raw != NULL, *((T *)NULL));
959 return m.raw[aIdx];
960#endif
961 }
962
963 /**
964 * Creates a copy of this array and stores it in a method parameter declared
965 * using the ComSafeArrayOut macro. When using this call, always wrap the
966 * parameter name in the ComSafeArrayOutArg macro call like this:
967 * <pre>
968 * safeArray.cloneTo(ComSafeArrayOutArg(aArg));
969 * </pre>
970 *
971 * @note It is assumed that the ownership of the returned copy is
972 * transferred to the caller of the method and he is responsible to free the
973 * array data when it is no longer needed.
974 *
975 * @param aArg Output method parameter to clone to.
976 */
977 virtual const SafeArray &cloneTo(ComSafeArrayOut(T, aArg)) const
978 {
979 /// @todo Implement me!
980#ifdef VBOX_WITH_XPCOM
981 NOREF(aArgSize);
982 NOREF(aArg);
983#else
984 NOREF(aArg);
985#endif
986 AssertFailedReturn(*this);
987 }
988
989 void cloneTo(SafeArray<T>& aOther) const
990 {
991 aOther.reset(size());
992 aOther.initFrom(*this);
993 }
994
995
996 /**
997 * Transfers the ownership of this array's data to the specified location
998 * declared using the ComSafeArrayOut macro and makes this array a null
999 * array. When using this call, always wrap the parameter name in the
1000 * ComSafeArrayOutArg macro call like this:
1001 * <pre>
1002 * safeArray.detachTo(ComSafeArrayOutArg(aArg));
1003 * </pre>
1004 *
1005 * Detaching the null array is also possible in which case the location will
1006 * receive NULL.
1007 *
1008 * @note Since the ownership of the array data is transferred to the
1009 * caller of the method, he is responsible to free the array data when it is
1010 * no longer needed.
1011 *
1012 * @param aArg Location to detach to.
1013 */
1014 virtual SafeArray &detachTo(ComSafeArrayOut(T, aArg))
1015 {
1016 AssertReturn(!m.isWeak, *this);
1017
1018#ifdef VBOX_WITH_XPCOM
1019
1020 AssertReturn(aArgSize != NULL, *this);
1021 AssertReturn(aArg != NULL, *this);
1022
1023 *aArgSize = m.size;
1024 *aArg = m.arr;
1025
1026 m.isWeak = false;
1027 m.size = 0;
1028 m.arr = NULL;
1029
1030#else /* !VBOX_WITH_XPCOM */
1031
1032 AssertReturn(aArg != NULL, *this);
1033 *aArg = m.arr;
1034
1035 if (m.raw)
1036 {
1037 HRESULT rc = SafeArrayUnaccessData(m.arr);
1038 AssertComRCReturn(rc, *this);
1039 m.raw = NULL;
1040 }
1041
1042 m.isWeak = false;
1043 m.arr = NULL;
1044
1045#endif /* !VBOX_WITH_XPCOM */
1046
1047 return *this;
1048 }
1049
1050 /**
1051 * Returns a copy of this SafeArray as RTCList<T>.
1052 */
1053 RTCList<T> toList()
1054 {
1055 RTCList<T> list(size());
1056 for (size_t i = 0; i < size(); ++i)
1057#ifdef VBOX_WITH_XPCOM
1058 list.append(m.arr[i]);
1059#else
1060 list.append(m.raw[i]);
1061#endif
1062 return list;
1063 }
1064
1065 inline void initFrom(const com::SafeArray<T> & aRef);
1066 inline void initFrom(const T* aPtr, size_t aSize);
1067
1068 // Public methods for internal purposes only.
1069
1070#ifdef VBOX_WITH_XPCOM
1071
1072 /** Internal function. Never call it directly. */
1073 PRUint32 *__asOutParam_Size() { setNull(); return &m.size; }
1074
1075 /** Internal function Never call it directly. */
1076 T **__asOutParam_Arr() { Assert(isNull()); return &m.arr; }
1077
1078#else /* !VBOX_WITH_XPCOM */
1079
1080 /** Internal function Never call it directly. */
1081 SAFEARRAY * __asInParam() { return m.arr; }
1082
1083 /** Internal function Never call it directly. */
1084 OutSafeArrayDipper __asOutParam()
1085 { setNull(); return OutSafeArrayDipper(&m.arr, (void **)&m.raw); }
1086
1087#endif /* !VBOX_WITH_XPCOM */
1088
1089 static const SafeArray Null;
1090
1091protected:
1092
1093 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(SafeArray)
1094
1095 /**
1096 * Ensures that the array is big enough to contain aNewSize elements.
1097 *
1098 * If the new size is greater than the current capacity, a new array is
1099 * allocated and elements from the old array are copied over. The size of
1100 * the array doesn't change, only the capacity increases (which is always
1101 * greater than the size). Note that the additionally allocated elements are
1102 * left uninitialized by this method.
1103 *
1104 * If the new size is less than the current size, the existing array is
1105 * truncated to the specified size and the elements outside the new array
1106 * boundary are freed.
1107 *
1108 * If the new size is the same as the current size, nothing happens.
1109 *
1110 * @param aNewSize New size of the array.
1111 *
1112 * @return @c true on success and @c false if not enough memory.
1113 */
1114 bool ensureCapacity(size_t aNewSize)
1115 {
1116 AssertReturn(!m.isWeak, false);
1117
1118#ifdef VBOX_WITH_XPCOM
1119
1120 /* Note: we distinguish between a null array and an empty (zero
1121 * elements) array. Therefore we never use zero in malloc (even if
1122 * aNewSize is zero) to make sure we get a non-null pointer. */
1123
1124 if (m.size == aNewSize && m.arr != NULL)
1125 return true;
1126
1127 /* Allocate in 16-byte pieces. */
1128 size_t newCapacity = RT_MAX((aNewSize + 15) / 16 * 16, 16);
1129
1130 if (m.capacity != newCapacity)
1131 {
1132 T *newArr = (T *)nsMemory::Alloc(RT_MAX(newCapacity, 1) * sizeof(T));
1133 AssertReturn(newArr != NULL, false);
1134
1135 if (m.arr != NULL)
1136 {
1137 if (m.size > aNewSize)
1138 {
1139 /* Truncation takes place, uninit exceeding elements and
1140 * shrink the size. */
1141 for (size_t i = aNewSize; i < m.size; ++ i)
1142 SafeArray::Uninit(m.arr[i]);
1143
1144 m.size = aNewSize;
1145 }
1146
1147 /* Copy the old contents. */
1148 memcpy(newArr, m.arr, m.size * sizeof(T));
1149 nsMemory::Free((void *)m.arr);
1150 }
1151
1152 m.arr = newArr;
1153 }
1154 else
1155 {
1156 if (m.size > aNewSize)
1157 {
1158 /* Truncation takes place, uninit exceeding elements and
1159 * shrink the size. */
1160 for (size_t i = aNewSize; i < m.size; ++ i)
1161 SafeArray::Uninit(m.arr[i]);
1162
1163 m.size = aNewSize;
1164 }
1165 }
1166
1167 m.capacity = newCapacity;
1168
1169#else
1170
1171 SAFEARRAYBOUND bound = { VarCount(aNewSize), 0 };
1172 HRESULT rc;
1173
1174 if (m.arr == NULL)
1175 {
1176 m.arr = CreateSafeArray(VarType(), &bound);
1177 AssertReturn(m.arr != NULL, false);
1178 }
1179 else
1180 {
1181 SafeArrayUnaccessData(m.arr);
1182
1183 rc = SafeArrayRedim(m.arr, &bound);
1184 AssertComRCReturn(rc == S_OK, false);
1185 }
1186
1187 rc = SafeArrayAccessData(m.arr, (void HUGEP **)&m.raw);
1188 AssertComRCReturn(rc, false);
1189
1190#endif
1191 return true;
1192 }
1193
1194 struct Data
1195 {
1196 Data()
1197 : isWeak(false)
1198#ifdef VBOX_WITH_XPCOM
1199 , capacity(0), size(0), arr(NULL)
1200#else
1201 , arr(NULL), raw(NULL)
1202#endif
1203 {}
1204
1205 ~Data() { uninit(); }
1206
1207 void uninit()
1208 {
1209#ifdef VBOX_WITH_XPCOM
1210
1211 if (arr)
1212 {
1213 if (!isWeak)
1214 {
1215 for (size_t i = 0; i < size; ++ i)
1216 SafeArray::Uninit(arr[i]);
1217
1218 nsMemory::Free((void *)arr);
1219 }
1220 else
1221 isWeak = false;
1222
1223 arr = NULL;
1224 }
1225
1226 size = capacity = 0;
1227
1228#else /* !VBOX_WITH_XPCOM */
1229
1230 if (arr)
1231 {
1232 if (raw)
1233 {
1234 SafeArrayUnaccessData(arr);
1235 raw = NULL;
1236 }
1237
1238 if (!isWeak)
1239 {
1240 HRESULT rc = SafeArrayDestroy(arr);
1241 AssertComRCReturnVoid(rc);
1242 }
1243 else
1244 isWeak = false;
1245
1246 arr = NULL;
1247 }
1248
1249#endif /* !VBOX_WITH_XPCOM */
1250 }
1251
1252 bool isWeak : 1;
1253
1254#ifdef VBOX_WITH_XPCOM
1255 PRUint32 capacity;
1256 PRUint32 size;
1257 T *arr;
1258#else
1259 SAFEARRAY *arr;
1260 T *raw;
1261#endif
1262 };
1263
1264 Data m;
1265};
1266
1267/* Few fast specializations for primitive array types */
1268template<>
1269inline void com::SafeArray<BYTE>::initFrom(const com::SafeArray<BYTE> & aRef)
1270{
1271 size_t sSize = aRef.size();
1272 resize(sSize);
1273 ::memcpy(raw(), aRef.raw(), sSize);
1274}
1275template<>
1276inline void com::SafeArray<BYTE>::initFrom(const BYTE* aPtr, size_t aSize)
1277{
1278 resize(aSize);
1279 ::memcpy(raw(), aPtr, aSize);
1280}
1281
1282
1283template<>
1284inline void com::SafeArray<SHORT>::initFrom(const com::SafeArray<SHORT> & aRef)
1285{
1286 size_t sSize = aRef.size();
1287 resize(sSize);
1288 ::memcpy(raw(), aRef.raw(), sSize * sizeof(SHORT));
1289}
1290template<>
1291inline void com::SafeArray<SHORT>::initFrom(const SHORT* aPtr, size_t aSize)
1292{
1293 resize(aSize);
1294 ::memcpy(raw(), aPtr, aSize * sizeof(SHORT));
1295}
1296
1297template<>
1298inline void com::SafeArray<USHORT>::initFrom(const com::SafeArray<USHORT> & aRef)
1299{
1300 size_t sSize = aRef.size();
1301 resize(sSize);
1302 ::memcpy(raw(), aRef.raw(), sSize * sizeof(USHORT));
1303}
1304template<>
1305inline void com::SafeArray<USHORT>::initFrom(const USHORT* aPtr, size_t aSize)
1306{
1307 resize(aSize);
1308 ::memcpy(raw(), aPtr, aSize * sizeof(USHORT));
1309}
1310
1311template<>
1312inline void com::SafeArray<LONG>::initFrom(const com::SafeArray<LONG> & aRef)
1313{
1314 size_t sSize = aRef.size();
1315 resize(sSize);
1316 ::memcpy(raw(), aRef.raw(), sSize * sizeof(LONG));
1317}
1318template<>
1319inline void com::SafeArray<LONG>::initFrom(const LONG* aPtr, size_t aSize)
1320{
1321 resize(aSize);
1322 ::memcpy(raw(), aPtr, aSize * sizeof(LONG));
1323}
1324
1325
1326////////////////////////////////////////////////////////////////////////////////
1327
1328#ifdef VBOX_WITH_XPCOM
1329
1330/**
1331 * Version of com::SafeArray for arrays of GUID.
1332 *
1333 * In MS COM, GUID arrays store GUIDs by value and therefore input arrays are
1334 * represented using |GUID *| and out arrays -- using |GUID **|. In XPCOM,
1335 * GUID arrays store pointers to nsID so that input arrays are |const nsID **|
1336 * and out arrays are |nsID ***|. Due to this difference, it is impossible to
1337 * work with arrays of GUID on both platforms by simply using com::SafeArray
1338 * <GUID>. This class is intended to provide some level of cross-platform
1339 * behavior.
1340 *
1341 * The basic usage pattern is basically similar to com::SafeArray<> except that
1342 * you use ComSafeGUIDArrayIn* and ComSafeGUIDArrayOut* macros instead of
1343 * ComSafeArrayIn* and ComSafeArrayOut*. Another important nuance is that the
1344 * raw() array type is different (nsID **, or GUID ** on XPCOM and GUID * on MS
1345 * COM) so it is recommended to use operator[] instead which always returns a
1346 * GUID by value.
1347 *
1348 * Note that due to const modifiers, you cannot use SafeGUIDArray for input GUID
1349 * arrays. Please use SafeConstGUIDArray for this instead.
1350 *
1351 * Other than mentioned above, the functionality of this class is equivalent to
1352 * com::SafeArray<>. See the description of that template and its methods for
1353 * more information.
1354 *
1355 * Output GUID arrays are handled by a separate class, SafeGUIDArrayOut, since
1356 * this class cannot handle them because of const modifiers.
1357 */
1358class SafeGUIDArray : public SafeArray<nsID *>
1359{
1360public:
1361
1362 typedef SafeArray<nsID *> Base;
1363
1364 class nsIDRef
1365 {
1366 public:
1367
1368 nsIDRef(nsID * &aVal) : mVal(aVal) {}
1369
1370 operator const nsID &() const { return mVal ? *mVal : *Empty; }
1371 operator nsID() const { return mVal ? *mVal : *Empty; }
1372
1373 const nsID *operator&() const { return mVal ? mVal : Empty; }
1374
1375 nsIDRef &operator= (const nsID &aThat)
1376 {
1377 if (mVal == NULL)
1378 Copy(&aThat, mVal);
1379 else
1380 *mVal = aThat;
1381 return *this;
1382 }
1383
1384 private:
1385
1386 nsID * &mVal;
1387
1388 static const nsID *Empty;
1389
1390 friend class SafeGUIDArray;
1391 };
1392
1393 /** See SafeArray<>::SafeArray(). */
1394 SafeGUIDArray() {}
1395
1396 /** See SafeArray<>::SafeArray(size_t). */
1397 SafeGUIDArray(size_t aSize) : Base(aSize) {}
1398
1399 /**
1400 * Array access operator that returns an array element by reference. As a
1401 * special case, the return value of this operator on XPCOM is an nsID (GUID)
1402 * reference, instead of an nsID pointer (the actual SafeArray template
1403 * argument), for compatibility with the MS COM version.
1404 *
1405 * The rest is equivalent to SafeArray<>::operator[].
1406 */
1407 nsIDRef operator[] (size_t aIdx)
1408 {
1409 Assert(m.arr != NULL);
1410 Assert(aIdx < size());
1411 return nsIDRef(m.arr[aIdx]);
1412 }
1413
1414 /**
1415 * Const version of #operator[] that returns an array element by value.
1416 */
1417 const nsID &operator[] (size_t aIdx) const
1418 {
1419 Assert(m.arr != NULL);
1420 Assert(aIdx < size());
1421 return m.arr[aIdx] ? *m.arr[aIdx] : *nsIDRef::Empty;
1422 }
1423};
1424
1425/**
1426 * Version of com::SafeArray for const arrays of GUID.
1427 *
1428 * This class is used to work with input GUID array parameters in method
1429 * implementations. See SafeGUIDArray for more details.
1430 */
1431class SafeConstGUIDArray : public SafeArray<const nsID *,
1432 SafeArrayTraits<nsID *> >
1433{
1434public:
1435
1436 typedef SafeArray<const nsID *, SafeArrayTraits<nsID *> > Base;
1437
1438 /** See SafeArray<>::SafeArray(). */
1439 SafeConstGUIDArray() {}
1440
1441 /* See SafeArray<>::SafeArray(ComSafeArrayIn(T, aArg)). */
1442 SafeConstGUIDArray(ComSafeGUIDArrayIn(aArg))
1443 : Base(ComSafeGUIDArrayInArg(aArg)) {}
1444
1445 /**
1446 * Array access operator that returns an array element by reference. As a
1447 * special case, the return value of this operator on XPCOM is nsID (GUID)
1448 * instead of nsID *, for compatibility with the MS COM version.
1449 *
1450 * The rest is equivalent to SafeArray<>::operator[].
1451 */
1452 const nsID &operator[] (size_t aIdx) const
1453 {
1454 AssertReturn(m.arr != NULL, **((const nsID * *)NULL));
1455 AssertReturn(aIdx < size(), **((const nsID * *)NULL));
1456 return *m.arr[aIdx];
1457 }
1458
1459private:
1460
1461 /* These are disabled because of const. */
1462 bool reset(size_t aNewSize) { NOREF(aNewSize); return false; }
1463};
1464
1465#else /* !VBOX_WITH_XPCOM */
1466
1467typedef SafeArray<GUID> SafeGUIDArray;
1468typedef SafeArray<const GUID, SafeArrayTraits<GUID> > SafeConstGUIDArray;
1469
1470#endif /* !VBOX_WITH_XPCOM */
1471
1472////////////////////////////////////////////////////////////////////////////////
1473
1474#ifdef VBOX_WITH_XPCOM
1475
1476template<class I>
1477struct SafeIfaceArrayTraits
1478{
1479protected:
1480
1481 static void Init(I * &aElem) { aElem = NULL; }
1482 static void Uninit(I * &aElem)
1483 {
1484 if (aElem)
1485 {
1486 aElem->Release();
1487 aElem = NULL;
1488 }
1489 }
1490
1491 static void Copy(I * aFrom, I * &aTo)
1492 {
1493 if (aFrom != NULL)
1494 {
1495 aTo = aFrom;
1496 aTo->AddRef();
1497 }
1498 else
1499 aTo = NULL;
1500 }
1501
1502public:
1503
1504 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
1505 static I **__asInParam_Arr(I **aArr) { return aArr; }
1506 static I **__asInParam_Arr(const I **aArr) { return const_cast<I **>(aArr); }
1507};
1508
1509#else /* !VBOX_WITH_XPCOM */
1510
1511template<class I>
1512struct SafeIfaceArrayTraits
1513{
1514protected:
1515
1516 static VARTYPE VarType() { return VT_DISPATCH; }
1517 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
1518 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
1519
1520 static void Copy(I * aFrom, I * &aTo)
1521 {
1522 if (aFrom != NULL)
1523 {
1524 aTo = aFrom;
1525 aTo->AddRef();
1526 }
1527 else
1528 aTo = NULL;
1529 }
1530
1531 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
1532 {
1533 NOREF(aVarType);
1534 return SafeArrayCreateEx(VT_DISPATCH, 1, aBound, (PVOID)&_ATL_IIDOF(I));
1535 }
1536};
1537
1538#endif /* !VBOX_WITH_XPCOM */
1539
1540////////////////////////////////////////////////////////////////////////////////
1541
1542/**
1543 * Version of com::SafeArray for arrays of interface pointers.
1544 *
1545 * Except that it manages arrays of interface pointers, the usage of this class
1546 * is identical to com::SafeArray.
1547 *
1548 * @param I Interface class (no asterisk).
1549 */
1550template<class I>
1551class SafeIfaceArray : public SafeArray<I *, SafeIfaceArrayTraits<I> >
1552{
1553public:
1554
1555 typedef SafeArray<I *, SafeIfaceArrayTraits<I> > Base;
1556
1557 /**
1558 * Creates a null array.
1559 */
1560 SafeIfaceArray() {}
1561
1562 /**
1563 * Creates a new array of the given size. All elements of the newly created
1564 * array initialized with null values.
1565 *
1566 * @param aSize Initial number of elements in the array. Must be greater
1567 * than 0.
1568 *
1569 * @note If this object remains null after construction it means that there
1570 * was not enough memory for creating an array of the requested size.
1571 * The constructor will also assert in this case.
1572 */
1573 SafeIfaceArray(size_t aSize) { Base::resize(aSize); }
1574
1575 /**
1576 * Weakly attaches this instance to the existing array passed in a method
1577 * parameter declared using the ComSafeArrayIn macro. When using this call,
1578 * always wrap the parameter name in the ComSafeArrayOutArg macro call like
1579 * this:
1580 * <pre>
1581 * SafeArray safeArray(ComSafeArrayInArg(aArg));
1582 * </pre>
1583 *
1584 * Note that this constructor doesn't take the ownership of the array. In
1585 * particular, this means that operations that operate on the ownership
1586 * (e.g. #detachTo()) are forbidden and will assert.
1587 *
1588 * @param aArg Input method parameter to attach to.
1589 */
1590 SafeIfaceArray(ComSafeArrayIn(I *, aArg))
1591 {
1592 if (aArg)
1593 {
1594#ifdef VBOX_WITH_XPCOM
1595
1596 Base::m.size = aArgSize;
1597 Base::m.arr = aArg;
1598 Base::m.isWeak = true;
1599
1600#else /* !VBOX_WITH_XPCOM */
1601
1602 SAFEARRAY *arg = aArg;
1603
1604 AssertReturnVoid(arg->cDims == 1);
1605
1606 VARTYPE vt;
1607 HRESULT rc = SafeArrayGetVartype(arg, &vt);
1608 AssertComRCReturnVoid(rc);
1609 AssertMsgReturnVoid(vt == VT_UNKNOWN || vt == VT_DISPATCH,
1610 ("Expected vartype VT_UNKNOWN or VT_DISPATCH, got %d.\n",
1611 vt));
1612 GUID guid;
1613 rc = SafeArrayGetIID(arg, &guid);
1614 AssertComRCReturnVoid(rc);
1615 AssertMsgReturnVoid(InlineIsEqualGUID(_ATL_IIDOF(I), guid),
1616 ("Expected IID {%RTuuid}, got {%RTuuid}.\n",
1617 &_ATL_IIDOF(I), &guid));
1618
1619 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
1620 AssertComRCReturnVoid(rc);
1621
1622 m.arr = arg;
1623 m.isWeak = true;
1624
1625#endif /* !VBOX_WITH_XPCOM */
1626 }
1627 }
1628
1629 /**
1630 * Creates a deep copy of the given standard C++ container that stores
1631 * interface pointers as objects of the ComPtr<I> class.
1632 *
1633 * @param aCntr Container object to copy.
1634 *
1635 * @param C Standard C++ container template class (normally deduced from
1636 * @c aCntr).
1637 * @param A Standard C++ allocator class (deduced from @c aCntr).
1638 * @param OI Argument to the ComPtr template (deduced from @c aCntr).
1639 */
1640 template<template<typename, typename> class C, class A, class OI>
1641 SafeIfaceArray(const C<ComPtr<OI>, A> & aCntr)
1642 {
1643 typedef C<ComPtr<OI>, A> List;
1644
1645 Base::resize(aCntr.size());
1646 AssertReturnVoid(!Base::isNull());
1647
1648 int i = 0;
1649 for (typename List::const_iterator it = aCntr.begin();
1650 it != aCntr.end(); ++ it, ++ i)
1651#ifdef VBOX_WITH_XPCOM
1652 this->Copy(*it, Base::m.arr[i]);
1653#else
1654 Copy(*it, Base::m.raw[i]);
1655#endif
1656 }
1657
1658 /**
1659 * Creates a deep copy of the given standard C++ container that stores
1660 * interface pointers as objects of the ComObjPtr<I> class.
1661 *
1662 * @param aCntr Container object to copy.
1663 *
1664 * @param C Standard C++ container template class (normally deduced from
1665 * @c aCntr).
1666 * @param A Standard C++ allocator class (deduced from @c aCntr).
1667 * @param OI Argument to the ComObjPtr template (deduced from @c aCntr).
1668 */
1669 template<template<typename, typename> class C, class A, class OI>
1670 SafeIfaceArray(const C<ComObjPtr<OI>, A> & aCntr)
1671 {
1672 typedef C<ComObjPtr<OI>, A> List;
1673
1674 Base::resize(aCntr.size());
1675 AssertReturnVoid(!Base::isNull());
1676
1677 int i = 0;
1678 for (typename List::const_iterator it = aCntr.begin();
1679 it != aCntr.end(); ++ it, ++ i)
1680#ifdef VBOX_WITH_XPCOM
1681 SafeIfaceArray::Copy(*it, Base::m.arr[i]);
1682#else
1683 Copy(*it, Base::m.raw[i]);
1684#endif
1685 }
1686
1687 /**
1688 * Creates a deep copy of the given standard C++ map whose values are
1689 * interface pointers stored as objects of the ComPtr<I> class.
1690 *
1691 * @param aMap Map object to copy.
1692 *
1693 * @param C Standard C++ map template class (normally deduced from
1694 * @c aCntr).
1695 * @param L Standard C++ compare class (deduced from @c aCntr).
1696 * @param A Standard C++ allocator class (deduced from @c aCntr).
1697 * @param K Map key class (deduced from @c aCntr).
1698 * @param OI Argument to the ComPtr template (deduced from @c aCntr).
1699 */
1700 template<template<typename, typename, typename, typename>
1701 class C, class L, class A, class K, class OI>
1702 SafeIfaceArray(const C<K, ComPtr<OI>, L, A> & aMap)
1703 {
1704 typedef C<K, ComPtr<OI>, L, A> Map;
1705
1706 Base::resize(aMap.size());
1707 AssertReturnVoid(!Base::isNull());
1708
1709 int i = 0;
1710 for (typename Map::const_iterator it = aMap.begin();
1711 it != aMap.end(); ++ it, ++ i)
1712#ifdef VBOX_WITH_XPCOM
1713 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1714#else
1715 Copy(it->second, Base::m.raw[i]);
1716#endif
1717 }
1718
1719 /**
1720 * Creates a deep copy of the given standard C++ map whose values are
1721 * interface pointers stored as objects of the ComObjPtr<I> class.
1722 *
1723 * @param aMap Map object to copy.
1724 *
1725 * @param C Standard C++ map template class (normally deduced from
1726 * @c aCntr).
1727 * @param L Standard C++ compare class (deduced from @c aCntr).
1728 * @param A Standard C++ allocator class (deduced from @c aCntr).
1729 * @param K Map key class (deduced from @c aCntr).
1730 * @param OI Argument to the ComObjPtr template (deduced from @c aCntr).
1731 */
1732 template<template<typename, typename, typename, typename>
1733 class C, class L, class A, class K, class OI>
1734 SafeIfaceArray(const C<K, ComObjPtr<OI>, L, A> & aMap)
1735 {
1736 typedef C<K, ComObjPtr<OI>, L, A> Map;
1737
1738 Base::resize(aMap.size());
1739 AssertReturnVoid(!Base::isNull());
1740
1741 int i = 0;
1742 for (typename Map::const_iterator it = aMap.begin();
1743 it != aMap.end(); ++ it, ++ i)
1744#ifdef VBOX_WITH_XPCOM
1745 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1746#else
1747 Copy(it->second, Base::m.raw[i]);
1748#endif
1749 }
1750
1751 void setElement(size_t iIdx, I* obj)
1752 {
1753#ifdef VBOX_WITH_XPCOM
1754 SafeIfaceArray::Copy(obj, Base::m.arr[iIdx]);
1755#else
1756 Copy(obj, Base::m.raw[iIdx]);
1757#endif
1758 }
1759};
1760
1761} /* namespace com */
1762
1763/** @} */
1764
1765#endif /* !___VBox_com_array_h */
1766
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