VirtualBox

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

Last change on this file since 58803 was 58110, checked in by vboxsync, 9 years ago

include,misc: Doxygen grouping adjustments, collecting all the VMM bits under one parent group, ditto for the COM library.

  • 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-2015 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
30/** @defgroup grp_com_arrays COM/XPCOM Arrays
31 * @ingroup grp_com
32 * @{
33 *
34 * The COM/XPCOM array support layer provides a cross-platform way to pass
35 * arrays to and from COM interface methods and consists of the com::SafeArray
36 * template and a set of ComSafeArray* macros part of which is defined in
37 * VBox/com/defs.h.
38 *
39 * This layer works with interface attributes and method parameters that have
40 * the 'safearray="yes"' attribute in the XIDL definition:
41 * @code
42
43 <interface name="ISomething" ...>
44
45 <method name="testArrays">
46 <param name="inArr" type="long" dir="in" safearray="yes"/>
47 <param name="outArr" type="long" dir="out" safearray="yes"/>
48 <param name="retArr" type="long" dir="return" safearray="yes"/>
49 </method>
50
51 </interface>
52
53 * @endcode
54 *
55 * Methods generated from this and similar definitions are implemented in
56 * component classes using the following declarations:
57 * @code
58
59 STDMETHOD(TestArrays)(ComSafeArrayIn(LONG, aIn),
60 ComSafeArrayOut(LONG, aOut),
61 ComSafeArrayOut(LONG, aRet));
62
63 * @endcode
64 *
65 * And the following function bodies:
66 * @code
67
68 STDMETHODIMP Component::TestArrays(ComSafeArrayIn(LONG, aIn),
69 ComSafeArrayOut(LONG, aOut),
70 ComSafeArrayOut(LONG, aRet))
71 {
72 if (ComSafeArrayInIsNull(aIn))
73 return E_INVALIDARG;
74 if (ComSafeArrayOutIsNull(aOut))
75 return E_POINTER;
76 if (ComSafeArrayOutIsNull(aRet))
77 return E_POINTER;
78
79 // Use SafeArray to access the input array parameter
80
81 com::SafeArray<LONG> in(ComSafeArrayInArg(aIn));
82
83 for (size_t i = 0; i < in.size(); ++ i)
84 LogFlow(("*** in[%u]=%d\n", i, in[i]));
85
86 // Use SafeArray to create the return array (the same technique is used
87 // for output array parameters)
88
89 SafeArray<LONG> ret(in.size() * 2);
90 for (size_t i = 0; i < in.size(); ++ i)
91 {
92 ret[i] = in[i];
93 ret[i + in.size()] = in[i] * 10;
94 }
95
96 ret.detachTo(ComSafeArrayOutArg(aRet));
97
98 return S_OK;
99 }
100
101 * @endcode
102 *
103 * Such methods can be called from the client code using the following pattern:
104 * @code
105
106 ComPtr<ISomething> component;
107
108 // ...
109
110 com::SafeArray<LONG> in(3);
111 in[0] = -1;
112 in[1] = -2;
113 in[2] = -3;
114
115 com::SafeArray<LONG> out;
116 com::SafeArray<LONG> ret;
117
118 HRESULT rc = component->TestArrays(ComSafeArrayAsInParam(in),
119 ComSafeArrayAsOutParam(out),
120 ComSafeArrayAsOutParam(ret));
121
122 if (SUCCEEDED(rc))
123 for (size_t i = 0; i < ret.size(); ++ i)
124 printf("*** ret[%u]=%d\n", i, ret[i]);
125
126 * @endcode
127 *
128 * For interoperability with standard C++ containers, there is a template
129 * constructor that takes such a container as argument and performs a deep copy
130 * of its contents. This can be used in method implementations like this:
131 * @code
132
133 STDMETHODIMP Component::COMGETTER(Values)(ComSafeArrayOut(int, aValues))
134 {
135 // ... assume there is a |std::list<int> mValues| data member
136
137 com::SafeArray<int> values(mValues);
138 values.detachTo(ComSafeArrayOutArg(aValues));
139
140 return S_OK;
141 }
142
143 * @endcode
144 *
145 * The current implementation of the SafeArray layer supports all types normally
146 * allowed in XIDL as array element types (including 'wstring' and 'uuid').
147 * However, 'pointer-to-...' types (e.g. 'long *', 'wstring *') are not
148 * supported and therefore cannot be used as element types.
149 *
150 * Note that for GUID arrays you should use SafeGUIDArray and
151 * SafeConstGUIDArray, customized SafeArray<> specializations.
152 *
153 * Also note that in order to pass input BSTR array parameters declared
154 * using the ComSafeArrayIn(IN_BSTR, aParam) macro to the SafeArray<>
155 * constructor using the ComSafeArrayInArg() macro, you should use IN_BSTR
156 * as the SafeArray<> template argument, not just BSTR.
157 *
158 * Arrays of interface pointers are also supported but they require to use a
159 * special SafeArray implementation, com::SafeIfacePointer, which takes the
160 * interface class name as a template argument (e.g.
161 * com::SafeIfacePointer\<IUnknown\>). This implementation functions
162 * identically to com::SafeArray.
163 */
164
165#ifdef VBOX_WITH_XPCOM
166# include <nsMemory.h>
167#endif
168
169 /* Type traits are a C++ 11 feature, so not available everywhere (yet). */
170 /* Only GCC 4.6 or newer. */
171#if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 406) \
172 /* Only MSVC++ 16.0 (Visual Studio 2010) or newer. */ \
173 || (defined(_MSC_VER) && (_MSC_VER >= 1600))
174 #define VBOX_WITH_TYPE_TRAITS
175#endif
176
177#ifdef VBOX_WITH_TYPE_TRAITS
178# include <type_traits>
179#endif
180
181#include "VBox/com/defs.h"
182#include "VBox/com/ptr.h"
183#include "VBox/com/assert.h"
184#include "iprt/cpp/list.h"
185
186#ifdef VBOX_WITH_XPCOM
187
188/**
189 * Wraps the given com::SafeArray instance to generate an expression that is
190 * suitable for passing it to functions that take input safearray parameters
191 * declared using the ComSafeArrayIn macro.
192 *
193 * @param aArray com::SafeArray instance to pass as an input parameter.
194 */
195#define ComSafeArrayAsInParam(aArray) \
196 (aArray).size(), (aArray).__asInParam_Arr((aArray).raw())
197
198/**
199 * Wraps the given com::SafeArray instance to generate an expression that is
200 * suitable for passing it to functions that take output safearray parameters
201 * declared using the ComSafeArrayOut macro.
202 *
203 * @param aArray com::SafeArray instance to pass as an output parameter.
204 */
205#define ComSafeArrayAsOutParam(aArray) \
206 (aArray).__asOutParam_Size(), (aArray).__asOutParam_Arr()
207
208#else /* !VBOX_WITH_XPCOM */
209
210#define ComSafeArrayAsInParam(aArray) (aArray).__asInParam()
211
212#define ComSafeArrayAsOutParam(aArray) (aArray).__asOutParam()
213
214#endif /* !VBOX_WITH_XPCOM */
215
216/**
217 *
218 */
219namespace com
220{
221
222#ifdef VBOX_WITH_XPCOM
223
224////////////////////////////////////////////////////////////////////////////////
225
226/**
227 * Provides various helpers for SafeArray.
228 *
229 * @param T Type of array elements.
230 */
231template<typename T>
232struct SafeArrayTraits
233{
234protected:
235
236 /** Initializes memory for aElem. */
237 static void Init(T &aElem) { aElem = 0; }
238
239 /** Initializes memory occupied by aElem. */
240 static void Uninit(T &aElem) { aElem = 0; }
241
242 /** Creates a deep copy of aFrom and stores it in aTo. */
243 static void Copy(const T &aFrom, T &aTo) { aTo = aFrom; }
244
245public:
246
247 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard (that
248 * in particular forbid casts of 'char **' to 'const char **'). Then initial
249 * reason for this magic is that XPIDL declares input strings
250 * (char/PRUnichar pointers) as const but doesn't do so for pointers to
251 * arrays. */
252 static T *__asInParam_Arr(T *aArr) { return aArr; }
253 static T *__asInParam_Arr(const T *aArr) { return const_cast<T *>(aArr); }
254};
255
256template<typename T>
257struct SafeArrayTraits<T *>
258{
259 // Arbitrary pointers are not supported
260};
261
262template<>
263struct SafeArrayTraits<PRUnichar *>
264{
265protected:
266
267 static void Init(PRUnichar * &aElem) { aElem = NULL; }
268
269 static void Uninit(PRUnichar * &aElem)
270 {
271 if (aElem)
272 {
273 ::SysFreeString(aElem);
274 aElem = NULL;
275 }
276 }
277
278 static void Copy(const PRUnichar * aFrom, PRUnichar * &aTo)
279 {
280 AssertCompile(sizeof(PRUnichar) == sizeof(OLECHAR));
281 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
282 }
283
284public:
285
286 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
287 static const PRUnichar **__asInParam_Arr(PRUnichar **aArr)
288 {
289 return const_cast<const PRUnichar **>(aArr);
290 }
291 static const PRUnichar **__asInParam_Arr(const PRUnichar **aArr) { return aArr; }
292};
293
294template<>
295struct SafeArrayTraits<const PRUnichar *>
296{
297protected:
298
299 static void Init(const PRUnichar * &aElem) { aElem = NULL; }
300 static void Uninit(const PRUnichar * &aElem)
301 {
302 if (aElem)
303 {
304 ::SysFreeString(const_cast<PRUnichar *>(aElem));
305 aElem = NULL;
306 }
307 }
308
309 static void Copy(const PRUnichar * aFrom, const PRUnichar * &aTo)
310 {
311 AssertCompile(sizeof(PRUnichar) == sizeof(OLECHAR));
312 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
313 }
314
315public:
316
317 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
318 static const PRUnichar **__asInParam_Arr(const PRUnichar **aArr) { return aArr; }
319};
320
321template<>
322struct SafeArrayTraits<nsID *>
323{
324protected:
325
326 static void Init(nsID * &aElem) { aElem = NULL; }
327
328 static void Uninit(nsID * &aElem)
329 {
330 if (aElem)
331 {
332 ::nsMemory::Free(aElem);
333 aElem = NULL;
334 }
335 }
336
337 static void Copy(const nsID * aFrom, nsID * &aTo)
338 {
339 if (aFrom)
340 {
341 aTo = (nsID *) ::nsMemory::Alloc(sizeof(nsID));
342 if (aTo)
343 *aTo = *aFrom;
344 }
345 else
346 aTo = NULL;
347 }
348
349 /* This specification is also reused for SafeConstGUIDArray, so provide a
350 * no-op Init() and Uninit() which are necessary for SafeArray<> but should
351 * be never called in context of SafeConstGUIDArray. */
352
353 static void Init(const nsID * &aElem) { NOREF(aElem); AssertFailed(); }
354 static void Uninit(const nsID * &aElem) { NOREF(aElem); AssertFailed(); }
355
356public:
357
358 /** Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
359 static const nsID **__asInParam_Arr(nsID **aArr)
360 {
361 return const_cast<const nsID **>(aArr);
362 }
363 static const nsID **__asInParam_Arr(const nsID **aArr) { return aArr; }
364};
365
366#else /* !VBOX_WITH_XPCOM */
367
368////////////////////////////////////////////////////////////////////////////////
369
370struct SafeArrayTraitsBase
371{
372protected:
373
374 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
375 { return SafeArrayCreate(aVarType, 1, aBound); }
376};
377
378/**
379 * Provides various helpers for SafeArray.
380 *
381 * @param T Type of array elements.
382 *
383 * Specializations of this template must provide the following methods:
384 *
385 // Returns the VARTYPE of COM SafeArray elements to be used for T
386 static VARTYPE VarType();
387
388 // Returns the number of VarType() elements necessary for aSize
389 // elements of T
390 static ULONG VarCount(size_t aSize);
391
392 // Returns the number of elements of T that fit into the given number of
393 // VarType() elements (opposite to VarCount(size_t aSize)).
394 static size_t Size(ULONG aVarCount);
395
396 // Creates a deep copy of aFrom and stores it in aTo
397 static void Copy(ULONG aFrom, ULONG &aTo);
398 */
399template<typename T>
400struct SafeArrayTraits : public SafeArrayTraitsBase
401{
402protected:
403
404 // Arbitrary types are treated as passed by value and each value is
405 // represented by a number of VT_Ix type elements where VT_Ix has the
406 // biggest possible bitness necessary to represent T w/o a gap. COM enums
407 // fall into this category.
408
409 static VARTYPE VarType()
410 {
411#ifdef VBOX_WITH_TYPE_TRAITS
412 if ( std::is_integral<T>::value
413 && !std::is_signed<T>::value)
414 {
415 if (sizeof(T) % 8 == 0) return VT_UI8;
416 if (sizeof(T) % 4 == 0) return VT_UI4;
417 if (sizeof(T) % 2 == 0) return VT_UI2;
418 return VT_UI1;
419 }
420#endif
421 if (sizeof(T) % 8 == 0) return VT_I8;
422 if (sizeof(T) % 4 == 0) return VT_I4;
423 if (sizeof(T) % 2 == 0) return VT_I2;
424 return VT_I1;
425 }
426
427 /*
428 * Fallback method in case type traits (VBOX_WITH_TYPE_TRAITS)
429 * are not available. Always returns unsigned types.
430 */
431 static VARTYPE VarTypeUnsigned()
432 {
433 if (sizeof(T) % 8 == 0) return VT_UI8;
434 if (sizeof(T) % 4 == 0) return VT_UI4;
435 if (sizeof(T) % 2 == 0) return VT_UI2;
436 return VT_UI1;
437 }
438
439 static ULONG VarCount(size_t aSize)
440 {
441 if (sizeof(T) % 8 == 0) return (ULONG)((sizeof(T) / 8) * aSize);
442 if (sizeof(T) % 4 == 0) return (ULONG)((sizeof(T) / 4) * aSize);
443 if (sizeof(T) % 2 == 0) return (ULONG)((sizeof(T) / 2) * aSize);
444 return (ULONG)(sizeof(T) * aSize);
445 }
446
447 static size_t Size(ULONG aVarCount)
448 {
449 if (sizeof(T) % 8 == 0) return (size_t)(aVarCount * 8) / sizeof(T);
450 if (sizeof(T) % 4 == 0) return (size_t)(aVarCount * 4) / sizeof(T);
451 if (sizeof(T) % 2 == 0) return (size_t)(aVarCount * 2) / sizeof(T);
452 return (size_t) aVarCount / sizeof(T);
453 }
454
455 static void Copy(T aFrom, T &aTo) { aTo = aFrom; }
456};
457
458template<typename T>
459struct SafeArrayTraits<T *>
460{
461 // Arbitrary pointer types are not supported
462};
463
464/* Although the generic SafeArrayTraits template would work for all integers,
465 * we specialize it for some of them in order to use the correct VT_ type */
466
467template<>
468struct SafeArrayTraits<LONG> : public SafeArrayTraitsBase
469{
470protected:
471
472 static VARTYPE VarType() { return VT_I4; }
473 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
474 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
475
476 static void Copy(LONG aFrom, LONG &aTo) { aTo = aFrom; }
477};
478
479template<>
480struct SafeArrayTraits<ULONG> : public SafeArrayTraitsBase
481{
482protected:
483
484 static VARTYPE VarType() { return VT_UI4; }
485 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
486 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
487
488 static void Copy(ULONG aFrom, ULONG &aTo) { aTo = aFrom; }
489};
490
491template<>
492struct SafeArrayTraits<LONG64> : public SafeArrayTraitsBase
493{
494protected:
495
496 static VARTYPE VarType() { return VT_I8; }
497 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
498 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
499
500 static void Copy(LONG64 aFrom, LONG64 &aTo) { aTo = aFrom; }
501};
502
503template<>
504struct SafeArrayTraits<ULONG64> : public SafeArrayTraitsBase
505{
506protected:
507
508 static VARTYPE VarType() { return VT_UI8; }
509 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
510 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
511
512 static void Copy(ULONG64 aFrom, ULONG64 &aTo) { aTo = aFrom; }
513};
514
515template<>
516struct SafeArrayTraits<BSTR> : public SafeArrayTraitsBase
517{
518protected:
519
520 static VARTYPE VarType() { return VT_BSTR; }
521 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
522 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
523
524 static void Copy(BSTR aFrom, BSTR &aTo)
525 {
526 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
527 }
528};
529
530template<>
531struct SafeArrayTraits<GUID> : public SafeArrayTraitsBase
532{
533protected:
534
535 /* Use the 64-bit unsigned integer type for GUID */
536 static VARTYPE VarType() { return VT_UI8; }
537
538 /* GUID is 128 bit, so we need two VT_UI8 */
539 static ULONG VarCount(size_t aSize)
540 {
541 AssertCompileSize(GUID, 16);
542 return (ULONG)(aSize * 2);
543 }
544
545 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount / 2; }
546
547 static void Copy(GUID aFrom, GUID &aTo) { aTo = aFrom; }
548};
549
550/**
551 * Helper for SafeArray::__asOutParam() that automatically updates m.raw after a
552 * non-NULL m.arr assignment.
553 */
554class OutSafeArrayDipper
555{
556 OutSafeArrayDipper(SAFEARRAY **aArr, void **aRaw)
557 : arr(aArr), raw(aRaw) { Assert(*aArr == NULL && *aRaw == NULL); }
558
559 SAFEARRAY **arr;
560 void **raw;
561
562 template<class, class> friend class SafeArray;
563
564public:
565
566 ~OutSafeArrayDipper()
567 {
568 if (*arr != NULL)
569 {
570 HRESULT rc = SafeArrayAccessData(*arr, raw);
571 AssertComRC(rc);
572 }
573 }
574
575 operator SAFEARRAY **() { return arr; }
576};
577
578#endif /* !VBOX_WITH_XPCOM */
579
580////////////////////////////////////////////////////////////////////////////////
581
582/**
583 * The SafeArray class represents the safe array type used in COM to pass arrays
584 * to/from interface methods.
585 *
586 * This helper class hides all MSCOM/XPCOM specific implementation details and,
587 * together with ComSafeArrayIn, ComSafeArrayOut and ComSafeArrayRet macros,
588 * provides a platform-neutral way to handle safe arrays in the method
589 * implementation.
590 *
591 * When an instance of this class is destroyed, it automatically frees all
592 * resources occupied by individual elements of the array as well as by the
593 * array itself. However, when the value of an element is manually changed
594 * using #operator[] or by accessing array data through the #raw() pointer, it is
595 * the caller's responsibility to free resources occupied by the previous
596 * element's value.
597 *
598 * Also, objects of this class do not support copy and assignment operations and
599 * therefore cannot be returned from functions by value. In other words, this
600 * class is just a temporary storage for handling interface method calls and not
601 * intended to be used to store arrays as data members and such -- you should
602 * use normal list/vector classes for that.
603 *
604 * @note The current implementation supports only one-dimensional arrays.
605 *
606 * @note This class is not thread-safe.
607 */
608template<typename T, class Traits = SafeArrayTraits<T> >
609class SafeArray : public Traits
610{
611public:
612
613 /**
614 * Creates a null array.
615 */
616 SafeArray() {}
617
618 /**
619 * Creates a new array of the given size. All elements of the newly created
620 * array initialized with null values.
621 *
622 * @param aSize Initial number of elements in the array.
623 *
624 * @note If this object remains null after construction it means that there
625 * was not enough memory for creating an array of the requested size.
626 * The constructor will also assert in this case.
627 */
628 SafeArray(size_t aSize) { resize(aSize); }
629
630 /**
631 * Weakly attaches this instance to the existing array passed in a method
632 * parameter declared using the ComSafeArrayIn macro. When using this call,
633 * always wrap the parameter name in the ComSafeArrayInArg macro call like
634 * this:
635 * <pre>
636 * SafeArray safeArray(ComSafeArrayInArg(aArg));
637 * </pre>
638 *
639 * Note that this constructor doesn't take the ownership of the array. In
640 * particular, it means that operations that operate on the ownership (e.g.
641 * #detachTo()) are forbidden and will assert.
642 *
643 * @param aArg Input method parameter to attach to.
644 */
645 SafeArray(ComSafeArrayIn(T, aArg))
646 {
647 if (aArg)
648 {
649#ifdef VBOX_WITH_XPCOM
650
651 m.size = aArgSize;
652 m.arr = aArg;
653 m.isWeak = true;
654
655#else /* !VBOX_WITH_XPCOM */
656
657 SAFEARRAY *arg = aArg;
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 m.arr = arg;
680 m.isWeak = true;
681
682#endif /* !VBOX_WITH_XPCOM */
683 }
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 * @tparam 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 * @tparam C Standard C++ map template class (normally deduced from
718 * @a aMap).
719 * @tparam L Standard C++ compare class (deduced from @a aMap).
720 * @tparam A Standard C++ allocator class (deduced from @a aMap).
721 * @tparam K Map key class (deduced from @a aMap).
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() instead. If
835 * you need to assign a copy of the existing value instead of transferring
836 * 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, *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 if (aArg)
1596 {
1597#ifdef VBOX_WITH_XPCOM
1598
1599 Base::m.size = aArgSize;
1600 Base::m.arr = aArg;
1601 Base::m.isWeak = true;
1602
1603#else /* !VBOX_WITH_XPCOM */
1604
1605 SAFEARRAY *arg = aArg;
1606
1607 AssertReturnVoid(arg->cDims == 1);
1608
1609 VARTYPE vt;
1610 HRESULT rc = SafeArrayGetVartype(arg, &vt);
1611 AssertComRCReturnVoid(rc);
1612 AssertMsgReturnVoid(vt == VT_UNKNOWN || vt == VT_DISPATCH,
1613 ("Expected vartype VT_UNKNOWN or VT_DISPATCH, got %d.\n",
1614 vt));
1615 GUID guid;
1616 rc = SafeArrayGetIID(arg, &guid);
1617 AssertComRCReturnVoid(rc);
1618 AssertMsgReturnVoid(InlineIsEqualGUID(_ATL_IIDOF(I), guid),
1619 ("Expected IID {%RTuuid}, got {%RTuuid}.\n",
1620 &_ATL_IIDOF(I), &guid));
1621
1622 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
1623 AssertComRCReturnVoid(rc);
1624
1625 m.arr = arg;
1626 m.isWeak = true;
1627
1628#endif /* !VBOX_WITH_XPCOM */
1629 }
1630 }
1631
1632 /**
1633 * Creates a deep copy of the given standard C++ container that stores
1634 * interface pointers as objects of the ComPtr\<I\> class.
1635 *
1636 * @param aCntr Container object to copy.
1637 *
1638 * @tparam C Standard C++ container template class (normally deduced from
1639 * @c aCntr).
1640 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1641 * @tparam OI Argument to the ComPtr template (deduced from @c aCntr).
1642 */
1643 template<template<typename, typename> class C, class A, class OI>
1644 SafeIfaceArray(const C<ComPtr<OI>, A> & aCntr)
1645 {
1646 typedef C<ComPtr<OI>, A> List;
1647
1648 Base::resize(aCntr.size());
1649 AssertReturnVoid(!Base::isNull());
1650
1651 int i = 0;
1652 for (typename List::const_iterator it = aCntr.begin();
1653 it != aCntr.end(); ++ it, ++ i)
1654#ifdef VBOX_WITH_XPCOM
1655 this->Copy(*it, Base::m.arr[i]);
1656#else
1657 Copy(*it, Base::m.raw[i]);
1658#endif
1659 }
1660
1661 /**
1662 * Creates a deep copy of the given standard C++ container that stores
1663 * interface pointers as objects of the ComObjPtr\<I\> class.
1664 *
1665 * @param aCntr Container object to copy.
1666 *
1667 * @tparam C Standard C++ container template class (normally deduced from
1668 * @c aCntr).
1669 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1670 * @tparam OI Argument to the ComObjPtr template (deduced from @c aCntr).
1671 */
1672 template<template<typename, typename> class C, class A, class OI>
1673 SafeIfaceArray(const C<ComObjPtr<OI>, A> & aCntr)
1674 {
1675 typedef C<ComObjPtr<OI>, A> List;
1676
1677 Base::resize(aCntr.size());
1678 AssertReturnVoid(!Base::isNull());
1679
1680 int i = 0;
1681 for (typename List::const_iterator it = aCntr.begin();
1682 it != aCntr.end(); ++ it, ++ i)
1683#ifdef VBOX_WITH_XPCOM
1684 SafeIfaceArray::Copy(*it, Base::m.arr[i]);
1685#else
1686 Copy(*it, Base::m.raw[i]);
1687#endif
1688 }
1689
1690 /**
1691 * Creates a deep copy of the given standard C++ map whose values are
1692 * interface pointers stored as objects of the ComPtr\<I\> class.
1693 *
1694 * @param aMap Map object to copy.
1695 *
1696 * @tparam C Standard C++ map template class (normally deduced from
1697 * @c aCntr).
1698 * @tparam L Standard C++ compare class (deduced from @c aCntr).
1699 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1700 * @tparam K Map key class (deduced from @c aCntr).
1701 * @tparam OI Argument to the ComPtr template (deduced from @c aCntr).
1702 */
1703 template<template<typename, typename, typename, typename>
1704 class C, class L, class A, class K, class OI>
1705 SafeIfaceArray(const C<K, ComPtr<OI>, L, A> & aMap)
1706 {
1707 typedef C<K, ComPtr<OI>, L, A> Map;
1708
1709 Base::resize(aMap.size());
1710 AssertReturnVoid(!Base::isNull());
1711
1712 int i = 0;
1713 for (typename Map::const_iterator it = aMap.begin();
1714 it != aMap.end(); ++ it, ++ i)
1715#ifdef VBOX_WITH_XPCOM
1716 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1717#else
1718 Copy(it->second, Base::m.raw[i]);
1719#endif
1720 }
1721
1722 /**
1723 * Creates a deep copy of the given standard C++ map whose values are
1724 * interface pointers stored as objects of the ComObjPtr\<I\> class.
1725 *
1726 * @param aMap Map object to copy.
1727 *
1728 * @tparam C Standard C++ map template class (normally deduced from
1729 * @c aCntr).
1730 * @tparam L Standard C++ compare class (deduced from @c aCntr).
1731 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1732 * @tparam K Map key class (deduced from @c aCntr).
1733 * @tparam OI Argument to the ComObjPtr template (deduced from @c aCntr).
1734 */
1735 template<template<typename, typename, typename, typename>
1736 class C, class L, class A, class K, class OI>
1737 SafeIfaceArray(const C<K, ComObjPtr<OI>, L, A> & aMap)
1738 {
1739 typedef C<K, ComObjPtr<OI>, L, A> Map;
1740
1741 Base::resize(aMap.size());
1742 AssertReturnVoid(!Base::isNull());
1743
1744 int i = 0;
1745 for (typename Map::const_iterator it = aMap.begin();
1746 it != aMap.end(); ++ it, ++ i)
1747#ifdef VBOX_WITH_XPCOM
1748 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1749#else
1750 Copy(it->second, Base::m.raw[i]);
1751#endif
1752 }
1753
1754 void setElement(size_t iIdx, I* obj)
1755 {
1756#ifdef VBOX_WITH_XPCOM
1757 SafeIfaceArray::Copy(obj, Base::m.arr[iIdx]);
1758#else
1759 Copy(obj, Base::m.raw[iIdx]);
1760#endif
1761 }
1762};
1763
1764} /* namespace com */
1765
1766/** @} */
1767
1768#endif /* !___VBox_com_array_h */
1769
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