VirtualBox

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

Last change on this file since 13908 was 13908, checked in by vboxsync, 16 years ago

Fixed include order, a bunch of GCC 3.3 warnings, OS/2 build.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 39.0 KB
Line 
1/** @file
2 * MS COM / XPCOM Abstraction Layer:
3 * Safe array helper class declaration
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31#ifndef ___VBox_com_array_h
32#define ___VBox_com_array_h
33
34/** @defgroup grp_COM_arrays COM/XPCOM Arrays
35 * @{
36 *
37 * The COM/XPCOM array support layer provides a cross-platform way to pass
38 * arrays to and from COM interface methods and consists of the com::SafeArray
39 * template and a set of ComSafeArray* macros part of which is defined in
40 * VBox/com/defs.h.
41 *
42 * This layer works with interface attributes and method parameters that have
43 * the 'safearray="yes"' attribute in the XIDL definition:
44 * @code
45
46 <interface name="ISomething" ...>
47
48 <method name="testArrays">
49 <param name="inArr" type="long" dir="in" safearray="yes"/>
50 <param name="outArr" type="long" dir="out" safearray="yes"/>
51 <param name="retArr" type="long" dir="return" safearray="yes"/>
52 </method>
53
54 </interface>
55
56 * @endcode
57 *
58 * Methods generated from this and similar definitions are implemented in
59 * component classes using the following declarations:
60 * @code
61
62 STDMETHOD(TestArrays) (ComSafeArrayIn (LONG, aIn),
63 ComSafeArrayOut (LONG, aOut),
64 ComSafeArrayOut (LONG, aRet));
65
66 * @endcode
67 *
68 * And the following function bodies:
69 * @code
70
71 STDMETHODIMP Component::TestArrays (ComSafeArrayIn (LONG, aIn),
72 ComSafeArrayOut (LONG, aOut),
73 ComSafeArrayOut (LONG, aRet))
74 {
75 if (ComSafeArrayInIsNull (aIn))
76 return E_INVALIDARG;
77 if (ComSafeArrayOutIsNull (aOut))
78 return E_POINTER;
79 if (ComSafeArrayOutIsNull (aRet))
80 return E_POINTER;
81
82 // Use SafeArray to access the input array parameter
83
84 com::SafeArray <LONG> in (ComSafeArrayInArg (aIn));
85
86 for (size_t i = 0; i < in.size(); ++ i)
87 LogFlow (("*** in[%u]=%d\n", i, in [i]));
88
89 // Use SafeArray to create the return array (the same technique is used
90 // for output array paramters)
91
92 SafeArray <LONG> ret (in.size() * 2);
93 for (size_t i = 0; i < in.size(); ++ i)
94 {
95 ret [i] = in [i];
96 ret [i + in.size()] = in [i] * 10;
97 }
98
99 ret.detachTo (ComSafeArrayOutArg (aRet));
100
101 return S_OK;
102 }
103
104 * @endcode
105 *
106 * Such methods can be called from the client code using the following pattern:
107 * @code
108
109 ComPtr <ISomething> component;
110
111 // ...
112
113 com::SafeArray <LONG> in (3);
114 in [0] = -1;
115 in [1] = -2;
116 in [2] = -3;
117
118 com::SafeArray <LONG> out;
119 com::SafeArray <LONG> ret;
120
121 HRESULT rc = component->TestArrays (ComSafeArrayAsInParam (in),
122 ComSafeArrayAsOutParam (out),
123 ComSafeArrayAsOutParam (ret));
124
125 if (SUCCEEDED (rc))
126 for (size_t i = 0; i < ret.size(); ++ i)
127 printf ("*** ret[%u]=%d\n", i, ret [i]);
128
129 * @endcode
130 *
131 * For interoperability with standard C++ containers, there is a template
132 * constructor that takes such a container as argument and performs a deep copy
133 * of its contents. This can be used in method implementations like this:
134 * @code
135
136 STDMETHODIMP Component::COMGETTER(Values) (ComSafeArrayOut (int, aValues))
137 {
138 // ... assume there is a |std::list <int> mValues| data member
139
140 com::SafeArray <int> values (mValues);
141 values.detachTo (ComSafeArrayOutArg (aValues));
142
143 return S_OK;
144 }
145
146 * @endcode
147 *
148 * The current implementation of the SafeArray layer supports all types normally
149 * allowed in XIDL as array element types (including 'wstring' and 'uuid').
150 * However, 'pointer-to-...' types (e.g. 'long *', 'wstring *') are not
151 * supported and therefore cannot be used as element types.
152 *
153 * Note that for GUID arrays you should use SafeGUIDArray and
154 * SafeConstGUIDArray, customized SafeArray<> specializations.
155 *
156 * Also note that in order to pass input BSTR array parameters declared
157 * using the ComSafeArrayIn (INPTR BSTR, aParam) macro to the SafeArray<>
158 * constructor using the ComSafeArrayInArg() macro, you should use INPTR BSTR
159 * as the SafeArray<> template argument, not just BSTR.
160 *
161 * Arrays of interface pointers are also supported but they require to use a
162 * special SafeArray implementation, com::SafeIfacePointer, which takes the
163 * interface class name as a template argument (e.g. com::SafeIfacePointer
164 * <IUnknown>). This implementation functions identically to com::SafeArray.
165 */
166
167#if defined (VBOX_WITH_XPCOM)
168# include <nsMemory.h>
169#endif
170
171#include "VBox/com/defs.h"
172#include "VBox/com/ptr.h"
173#include "VBox/com/assert.h"
174
175#include "iprt/cpputils.h"
176
177#if defined (VBOX_WITH_XPCOM)
178
179/**
180 * Wraps the given com::SafeArray instance to generate an expression that is
181 * suitable for passing it to functions that take input safearray parameters
182 * declared using the ComSafeArrayIn macro.
183 *
184 * @param aArray com::SafeArray instance to pass as an input parameter.
185 */
186#define ComSafeArrayAsInParam(aArray) \
187 (aArray).size(), (aArray).__asInParam_Arr ((aArray).raw())
188
189/**
190 * Wraps the given com::SafeArray instance to generate an expression that is
191 * suitable for passing it to functions that take output safearray parameters
192 * declared using the ComSafeArrayOut macro.
193 *
194 * @param aArray com::SafeArray instance to pass as an output parameter.
195 */
196#define ComSafeArrayAsOutParam(aArray) \
197 (aArray).__asOutParam_Size(), (aArray).__asOutParam_Arr()
198
199#else /* defined (VBOX_WITH_XPCOM) */
200
201#define ComSafeArrayAsInParam(aArray) (aArray).__asInParam()
202
203#define ComSafeArrayAsOutParam(aArray) (aArray).__asOutParam()
204
205#endif /* defined (VBOX_WITH_XPCOM) */
206
207/**
208 *
209 */
210namespace com
211{
212
213#if defined (VBOX_WITH_XPCOM)
214
215////////////////////////////////////////////////////////////////////////////////
216
217/**
218 * Provides various helpers for SafeArray.
219 *
220 * @param T Type of array elements.
221 */
222template <typename T>
223struct SafeArrayTraits
224{
225protected:
226
227 /** Initializes memory for aElem. */
228 static void Init (T &aElem) { aElem = 0; }
229
230 /** Initializes memory occupied by aElem. */
231 static void Uninit (T &aElem) { aElem = 0; }
232
233 /** Creates a deep copy of aFrom and stores it in aTo. */
234 static void Copy (const T &aFrom, T &aTo) { aTo = aFrom; }
235
236public:
237
238 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard (that
239 * in particular forbid casts of 'char **' to 'const char **'). Then initial
240 * reason for this magic is that XPIDL declares input strings
241 * (char/PRUnichar pointers) as const but doesn't do so for pointers to
242 * arrays. */
243 static T *__asInParam_Arr (T *aArr) { return aArr; }
244 static T *__asInParam_Arr (const T *aArr) { return const_cast <T *> (aArr); }
245};
246
247template <typename T>
248struct SafeArrayTraits <T *>
249{
250 // Arbitrary pointers are not supported
251};
252
253template<>
254struct SafeArrayTraits <PRUnichar *>
255{
256protected:
257
258 static void Init (PRUnichar * &aElem) { aElem = NULL; }
259
260 static void Uninit (PRUnichar * &aElem)
261 {
262 if (aElem)
263 {
264 ::SysFreeString (aElem);
265 aElem = NULL;
266 }
267 }
268
269 static void Copy (const PRUnichar * aFrom, PRUnichar * &aTo)
270 {
271 AssertCompile (sizeof (PRUnichar) == sizeof (OLECHAR));
272 aTo = aFrom ? ::SysAllocString ((const OLECHAR *) aFrom) : NULL;
273 }
274
275public:
276
277 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
278 static const PRUnichar **__asInParam_Arr (PRUnichar **aArr)
279 {
280 return const_cast <const PRUnichar **> (aArr);
281 }
282 static const PRUnichar **__asInParam_Arr (const PRUnichar **aArr) { return aArr; }
283};
284
285template<>
286struct SafeArrayTraits <const PRUnichar *>
287{
288protected:
289
290 static void Init (const PRUnichar * &aElem) { aElem = NULL; }
291 static void Uninit (const PRUnichar * &aElem)
292 {
293 if (aElem)
294 {
295 ::SysFreeString (const_cast <PRUnichar *> (aElem));
296 aElem = NULL;
297 }
298 }
299
300 static void Copy (const PRUnichar * aFrom, const PRUnichar * &aTo)
301 {
302 AssertCompile (sizeof (PRUnichar) == sizeof (OLECHAR));
303 aTo = aFrom ? ::SysAllocString ((const OLECHAR *) aFrom) : NULL;
304 }
305
306public:
307
308 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
309 static const PRUnichar **__asInParam_Arr (const PRUnichar **aArr) { return aArr; }
310};
311
312template<>
313struct SafeArrayTraits <nsID *>
314{
315protected:
316
317 static void Init (nsID * &aElem) { aElem = NULL; }
318
319 static void Uninit (nsID * &aElem)
320 {
321 if (aElem)
322 {
323 ::nsMemory::Free (aElem);
324 aElem = NULL;
325 }
326 }
327
328 static void Copy (const nsID * aFrom, nsID * &aTo)
329 {
330 if (aFrom)
331 {
332 aTo = (nsID *) ::nsMemory::Alloc (sizeof (nsID));
333 if (aTo)
334 *aTo = *aFrom;
335 }
336 else
337 aTo = NULL;
338 }
339
340 /* This specification is also reused for SafeConstGUIDArray, so provide a
341 * no-op Init() and Uninit() which are necessary for SafeArray<> but should
342 * be never called in context of SafeConstGUIDArray. */
343
344 static void Init (const nsID * &aElem) { NOREF (aElem); AssertFailed(); }
345 static void Uninit (const nsID * &aElem) { NOREF (aElem); AssertFailed(); }
346
347public:
348
349 /** Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
350 static const nsID **__asInParam_Arr (nsID **aArr)
351 {
352 return const_cast <const nsID **> (aArr);
353 }
354 static const nsID **__asInParam_Arr (const nsID **aArr) { return aArr; }
355};
356
357#else /* defined (VBOX_WITH_XPCOM) */
358
359////////////////////////////////////////////////////////////////////////////////
360
361/**
362 * Provides various helpers for SafeArray.
363 *
364 * @param T Type of array elements.
365 *
366 * Specializations of this template must provide the following methods:
367 *
368 // Returns the VARTYPE of COM SafeArray elements to be used for T
369 static VARTYPE VarType();
370
371 // Returns the number of VarType() elements necessary for aSize
372 // elements of T
373 static ULONG VarCount (size_t aSize);
374
375 // Returns the number of elements of T that occupy the given number of
376 // VarType() elements (opposite to VarCount (size_t aSize)).
377 static size_t Size (ULONG aVarCount);
378
379 // Creates a deep copy of aFrom and stores it in aTo
380 static void Copy (ULONG aFrom, ULONG &aTo);
381 */
382template <typename T>
383struct SafeArrayTraits
384{
385 // Arbitrary types are not supported -- no helpers
386};
387
388template<>
389struct SafeArrayTraits <LONG>
390{
391protected:
392
393 static VARTYPE VarType() { return VT_I4; }
394 static ULONG VarCount (size_t aSize) { return (ULONG) aSize; }
395 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount; }
396
397 static void Copy (LONG aFrom, LONG &aTo) { aTo = aFrom; }
398};
399
400template<>
401struct SafeArrayTraits <ULONG>
402{
403protected:
404
405 static VARTYPE VarType() { return VT_UI4; }
406 static ULONG VarCount (size_t aSize) { return (ULONG) aSize; }
407 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount; }
408
409 static void Copy (ULONG aFrom, ULONG &aTo) { aTo = aFrom; }
410};
411
412template<>
413struct SafeArrayTraits <LONG64>
414{
415protected:
416
417 static VARTYPE VarType() { return VT_I8; }
418 static ULONG VarCount (size_t aSize) { return (ULONG) aSize; }
419 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount; }
420
421 static void Copy (LONG64 aFrom, LONG64 &aTo) { aTo = aFrom; }
422};
423
424template<>
425struct SafeArrayTraits <ULONG64>
426{
427protected:
428
429 static VARTYPE VarType() { return VT_UI8; }
430 static ULONG VarCount (size_t aSize) { return (ULONG) aSize; }
431 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount; }
432
433 static void Copy (ULONG64 aFrom, ULONG64 &aTo) { aTo = aFrom; }
434};
435
436template<>
437struct SafeArrayTraits <BSTR>
438{
439protected:
440
441 static VARTYPE VarType() { return VT_BSTR; }
442 static ULONG VarCount (size_t aSize) { return (ULONG) aSize; }
443 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount; }
444
445 static void Copy (BSTR aFrom, BSTR &aTo)
446 {
447 aTo = aFrom ? ::SysAllocString ((const OLECHAR *) aFrom) : NULL;
448 }
449};
450
451template<>
452struct SafeArrayTraits <GUID>
453{
454protected:
455
456 /* Use the 64-bit unsigned integer type for GUID */
457 static VARTYPE VarType() { return VT_UI8; }
458
459 /* GUID is 128 bit, so we need two VT_UI8 */
460 static ULONG VarCount (size_t aSize)
461 {
462 AssertCompileSize (GUID, 16);
463 return (ULONG) (aSize * 2);
464 }
465
466 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount / 2; }
467
468 static void Copy (GUID aFrom, GUID &aTo) { aTo = aFrom; }
469};
470
471#endif /* defined (VBOX_WITH_XPCOM) */
472
473////////////////////////////////////////////////////////////////////////////////
474
475/**
476 * The SafeArray class represents the safe array type used in COM to pass arrays
477 * to/from interface methods.
478 *
479 * This helper class hides all MSCOM/XPCOM specific implementation details and,
480 * together with ComSafeArrayIn, ComSafeArrayOut and ComSafeArrayRet macros,
481 * provides a platform-neutral way to handle safe arrays in the method
482 * implementation.
483 *
484 * When an instance of this class is destroyed, it automatically frees all
485 * resources occupied by individual elements of the array as well as by the
486 * array itself. However, when the value of an element is manually changed
487 * using #operator[] or by accessing array data through the #raw() pointer, it is
488 * the caller's responsibility to free resources occupied by the previous
489 * element's value.
490 *
491 * Also, objects of this class do not support copy and assignment operations and
492 * therefore cannot be returned from functions by value. In other words, this
493 * class is just a temporary storage for handling interface method calls and not
494 * intended to be used to store arrays as data members and such -- you should
495 * use normal list/vector classes for that.
496 *
497 * @note The current implementation supports only one-dimensional arrays.
498 *
499 * @note This class is not thread-safe.
500 */
501template <typename T, class Traits = SafeArrayTraits <T> >
502class SafeArray : public Traits
503{
504public:
505
506 /**
507 * Creates a null array.
508 */
509 SafeArray() {}
510
511 /**
512 * Creates a new array of the given size. All elements of the newly created
513 * array initialized with null values.
514 *
515 * @param aSize Initial number of elements in the array. Must be greater
516 * than 0.
517 *
518 * @note If this object remains null after construction it means that there
519 * was not enough memory for creating an array of the requested size.
520 * The constructor will also assert in this case.
521 */
522 SafeArray (size_t aSize) { reset (aSize); }
523
524 /**
525 * Weakly attaches this instance to the existing array passed in a method
526 * parameter declared using the ComSafeArrayIn macro. When using this call,
527 * always wrap the parameter name in the ComSafeArrayInArg macro call like
528 * this:
529 * <pre>
530 * SafeArray safeArray (ComSafeArrayInArg (aArg));
531 * </pre>
532 *
533 * Note that this constructor doesn't take the ownership of the array. In
534 * particular, it means that operations that operate on the ownership (e.g.
535 * #detachTo()) are forbidden and will assert.
536 *
537 * @param aArg Input method parameter to attach to.
538 */
539 SafeArray (ComSafeArrayIn (T, aArg))
540 {
541#if defined (VBOX_WITH_XPCOM)
542
543 AssertReturnVoid (aArg != NULL);
544
545 m.size = aArgSize;
546 m.arr = aArg;
547 m.isWeak = true;
548
549#else /* defined (VBOX_WITH_XPCOM) */
550
551 AssertReturnVoid (aArg != NULL);
552 SAFEARRAY *arg = *aArg;
553
554 if (arg)
555 {
556 AssertReturnVoid (arg->cDims == 1);
557
558 VARTYPE vt;
559 HRESULT rc = SafeArrayGetVartype (arg, &vt);
560 AssertComRCReturnVoid (rc);
561 AssertMsgReturnVoid (vt == VarType(),
562 ("Expected vartype %d, got %d.\n",
563 VarType(), vt));
564 }
565
566 m.arr = arg;
567 m.isWeak = true;
568
569 AssertReturnVoid (m.arr == NULL || accessRaw() != NULL);
570
571#endif /* defined (VBOX_WITH_XPCOM) */
572 }
573
574 /**
575 * Creates a deep copy of the given standard C++ container.
576 *
577 * @param aCntr Container object to copy.
578 *
579 * @param C Standard C++ container template class (normally deduced from
580 * @c aCntr).
581 */
582 template <template <typename, typename> class C, class A>
583 SafeArray (const C <T, A> & aCntr)
584 {
585 reset (aCntr.size());
586 AssertReturnVoid (!isNull());
587
588 size_t i = 0;
589 for (typename C <T, A>::const_iterator it = aCntr.begin();
590 it != aCntr.end(); ++ it, ++ i)
591#if defined (VBOX_WITH_XPCOM)
592 Copy (*it, m.arr [i]);
593#else
594 Copy (*it, m.raw [i]);
595#endif
596 }
597
598 /**
599 * Destroys this instance after calling #setNull() to release allocated
600 * resources. See #setNull() for more details.
601 */
602 virtual ~SafeArray() { setNull(); }
603
604 /**
605 * Returns @c true if this instance represents a null array.
606 */
607 bool isNull() const { return m.arr == NULL; }
608
609 /**
610 * Resets this instance to null and, if this instance is not a weak one,
611 * releases any resources occupied by the array data.
612 *
613 * @note This method destroys (cleans up) all elements of the array using
614 * the corresponding cleanup routine for the element type before the
615 * array itself is destroyed.
616 */
617 virtual void setNull() { m.uninit(); }
618
619 /**
620 * Returns @c true if this instance is weak. A weak instance doesn't own the
621 * array data and therefore operations manipulating the ownership (e.g.
622 * #detachTo()) are forbidden and will assert.
623 */
624 bool isWeak() const { return m.isWeak; }
625
626 /** Number of elements in the array. */
627 size_t size() const
628 {
629#if defined (VBOX_WITH_XPCOM)
630 if (m.arr)
631 return m.size;
632 return 0;
633#else
634 if (m.arr)
635 return Size (m.arr->rgsabound [0].cElements);
636 return 0;
637#endif
638 }
639
640 /**
641 * Resizes the array preserving its contents when possible. If the new size
642 * is bigger than the old size, new elements are initialized with null
643 * values. If the new size is smaller than the old size, the contents of the
644 * array above the new size is lost.
645 *
646 * @param aNewSize New number of elements in the array.
647 * @return @c true on success and false if there is not enough
648 * memory for resizing.
649 */
650 virtual bool resize (size_t aNewSize)
651 {
652 /// @todo Implement me!
653 NOREF (aNewSize);
654 AssertFailedReturn (false);
655 }
656
657 /**
658 * Reinitializes this instance by preallocating space for the given number
659 * of elements. The previous array contents is lost.
660 *
661 * @param aNewSize New number of elements in the array.
662 * @return @c true on success and false if there is not enough
663 * memory for resizing.
664 */
665 virtual bool reset (size_t aNewSize)
666 {
667 m.uninit();
668
669#if defined (VBOX_WITH_XPCOM)
670
671 /* Note: for zero-sized arrays, we use the size of 1 because whether
672 * malloc(0) returns a null pointer or not (which is used in isNull())
673 * is implementation-dependent according to the C standard. */
674
675 m.arr = (T *) nsMemory::Alloc (RT_MAX (aNewSize, 1) * sizeof (T));
676 AssertReturn (m.arr != NULL, false);
677
678 m.size = aNewSize;
679
680 for (size_t i = 0; i < m.size; ++ i)
681 Init (m.arr [i]);
682
683#else
684
685 SAFEARRAYBOUND bound = { VarCount (aNewSize), 0 };
686 m.arr = SafeArrayCreate (VarType(), 1, &bound);
687 AssertReturn (m.arr != NULL, false);
688
689 AssertReturn (accessRaw() != NULL, false);
690
691#endif
692 return true;
693 }
694
695 /**
696 * Returns a pointer to the raw array data. Use this raw pointer with care
697 * as no type or bound checking is done for you in this case.
698 *
699 * @note This method returns @c NULL when this instance is null.
700 * @see #operator[]
701 */
702 T *raw()
703 {
704#if defined (VBOX_WITH_XPCOM)
705 return m.arr;
706#else
707 return accessRaw();
708#endif
709 }
710
711 /**
712 * Const version of #raw().
713 */
714 const T *raw() const
715 {
716#if defined (VBOX_WITH_XPCOM)
717 return m.arr;
718#else
719 return accessRaw();
720#endif
721 }
722
723 /**
724 * Array access operator that returns an array element by reference. A bit
725 * safer than #raw(): asserts and returns an invalid reference if this
726 * instance is null or if the index is out of bounds.
727 *
728 * @note For weak instances, this call will succeed but the behavior of
729 * changing the contents of an element of the weak array instance is
730 * undefined and may lead to a program crash on some platforms.
731 */
732 T &operator[] (size_t aIdx)
733 {
734 AssertReturn (m.arr != NULL, *((T *) NULL));
735 AssertReturn (aIdx < size(), *((T *) NULL));
736#if defined (VBOX_WITH_XPCOM)
737 return m.arr [aIdx];
738#else
739
740 AssertReturn (accessRaw() != NULL, *((T *) NULL));
741 return m.raw [aIdx];
742#endif
743 }
744
745 /**
746 * Const version of #operator[] that returns an array element by value.
747 */
748 const T operator[] (size_t aIdx) const
749 {
750 AssertReturn (m.arr != NULL, *((T *) NULL));
751 AssertReturn (aIdx < size(), *((T *) NULL));
752#if defined (VBOX_WITH_XPCOM)
753 return m.arr [aIdx];
754#else
755 AssertReturn (unconst (this)->accessRaw() != NULL, *((T *) NULL));
756 return m.raw [aIdx];
757#endif
758 }
759
760 /**
761 * Creates a copy of this array and stores it in a method parameter declared
762 * using the ComSafeArrayOut macro. When using this call, always wrap the
763 * parameter name in the ComSafeArrayOutArg macro call like this:
764 * <pre>
765 * safeArray.cloneTo (ComSafeArrayOutArg (aArg));
766 * </pre>
767 *
768 * @note It is assumed that the ownership of the returned copy is
769 * transferred to the caller of the method and he is responsible to free the
770 * array data when it is no more necessary.
771 *
772 * @param aArg Output method parameter to clone to.
773 */
774 virtual const SafeArray &cloneTo (ComSafeArrayOut (T, aArg)) const
775 {
776 /// @todo Implement me!
777#if defined (VBOX_WITH_XPCOM)
778 NOREF (aArgSize);
779 NOREF (aArg);
780#else
781 NOREF (aArg);
782#endif
783 AssertFailedReturn (*this);
784 }
785
786 /**
787 * Transfers the ownership of this array's data to the specified location
788 * declared using the ComSafeArrayOut macro and makes this array a null
789 * array. When using this call, always wrap the parameter name in the
790 * ComSafeArrayOutArg macro call like this:
791 * <pre>
792 * safeArray.detachTo (ComSafeArrayOutArg (aArg));
793 * </pre>
794 *
795 * Detaching the null array is also possible in which case the location will
796 * receive NULL.
797 *
798 * @note Since the ownership of the array data is transferred to the
799 * caller of the method, he is responsible to free the array data when it is
800 * no more necessary.
801 *
802 * @param aArg Location to detach to.
803 */
804 virtual SafeArray &detachTo (ComSafeArrayOut (T, aArg))
805 {
806 AssertReturn (m.isWeak == false, *this);
807
808#if defined (VBOX_WITH_XPCOM)
809
810 AssertReturn (aArgSize != NULL, *this);
811 AssertReturn (aArg != NULL, *this);
812
813 *aArgSize = m.size;
814 *aArg = m.arr;
815
816 m.isWeak = false;
817 m.size = 0;
818 m.arr = NULL;
819
820#else /* defined (VBOX_WITH_XPCOM) */
821
822 AssertReturn (aArg != NULL, *this);
823 *aArg = m.arr;
824
825 if (m.raw)
826 {
827 HRESULT rc = SafeArrayUnaccessData (m.arr);
828 AssertComRCReturn (rc, *this);
829 m.raw = NULL;
830 }
831
832 m.isWeak = false;
833 m.arr = NULL;
834
835#endif /* defined (VBOX_WITH_XPCOM) */
836
837 return *this;
838 }
839
840 // public methods for internal purposes only
841
842#if defined (VBOX_WITH_XPCOM)
843
844 /** Internal function. Never call it directly. */
845 PRUint32 *__asOutParam_Size() { setNull(); return &m.size; }
846
847 /** Internal function Never call it directly. */
848 T **__asOutParam_Arr() { Assert (isNull()); return &m.arr; }
849
850#else /* defined (VBOX_WITH_XPCOM) */
851
852 /** Internal function Never call it directly. */
853 SAFEARRAY ** __asInParam() { return &m.arr; }
854
855 /** Internal function Never call it directly. */
856 SAFEARRAY ** __asOutParam() { setNull(); return &m.arr; }
857
858#endif /* defined (VBOX_WITH_XPCOM) */
859
860 static const SafeArray Null;
861
862protected:
863
864 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(SafeArray)
865
866#if defined (VBOX_WITH_XPCOM)
867#else /* defined (VBOX_WITH_XPCOM) */
868
869 /** Requests access to the raw data pointer. */
870 T *accessRaw()
871 {
872 if (m.arr && m.raw == NULL)
873 {
874 HRESULT rc = SafeArrayAccessData (m.arr, (void HUGEP **) &m.raw);
875 AssertComRCReturn (rc, NULL);
876 }
877 return m.raw;
878 }
879
880#endif /* defined (VBOX_WITH_XPCOM) */
881
882 struct Data
883 {
884 Data()
885 : isWeak (false)
886#if defined (VBOX_WITH_XPCOM)
887 , size (0), arr (NULL)
888#else
889 , arr (NULL), raw (NULL)
890#endif
891 {}
892
893 ~Data() { uninit(); }
894
895 void uninit()
896 {
897#if defined (VBOX_WITH_XPCOM)
898
899 if (arr)
900 {
901 if (!isWeak)
902 {
903 for (size_t i = 0; i < size; ++ i)
904 Uninit (arr [i]);
905
906 nsMemory::Free ((void *) arr);
907
908 isWeak = false;
909 }
910 arr = NULL;
911 }
912
913#else /* defined (VBOX_WITH_XPCOM) */
914
915 if (arr)
916 {
917 if (raw)
918 {
919 SafeArrayUnaccessData (arr);
920 raw = NULL;
921 }
922
923 if (!isWeak)
924 {
925 HRESULT rc = SafeArrayDestroy (arr);
926 AssertComRCReturnVoid (rc);
927
928 isWeak = false;
929 }
930 arr = NULL;
931 }
932
933#endif /* defined (VBOX_WITH_XPCOM) */
934 }
935
936 bool isWeak : 1;
937
938#if defined (VBOX_WITH_XPCOM)
939 PRUint32 size;
940 T *arr;
941#else
942 SAFEARRAY *arr;
943 T *raw;
944#endif
945 };
946
947 Data m;
948};
949
950////////////////////////////////////////////////////////////////////////////////
951
952#if defined (VBOX_WITH_XPCOM)
953
954/**
955 * Version of com::SafeArray for arrays of GUID.
956 *
957 * In MS COM, GUID arrays store GUIDs by value and therefore input arrays are
958 * represented using |GUID *| and out arrays -- using |GUID **|. In XPCOM,
959 * GUID arrays store pointers to nsID so that input arrays are |const nsID **|
960 * and out arrays are |nsID ***|. Due to this difference, it is impossible to
961 * work with arrays of GUID on both platforms by simply using com::SafeArray
962 * <GUID>. This class is intended to provide some level of cross-platform
963 * behavior.
964 *
965 * The basic usage pattern is basically similar to com::SafeArray<> except that
966 * you use ComSafeGUIDArrayIn* and ComSafeGUIDArrayOut* macros instead of
967 * ComSafeArrayIn* and ComSafeArrayOut*. Another important nuance is that the
968 * raw() array type is different (nsID **, or GUID ** on XPCOM and GUID * on MS
969 * COM) so it is recommended to use operator[] instead that always returns a
970 * GUID by value.
971 *
972 * Note that due to const modifiers, you cannot use SafeGUIDArray for input GUID
973 * arrays. Please use SafeConstGUIDArray for this instead.
974 *
975 * Other than mentioned above, the functionality of this class is equivalent to
976 * com::SafeArray<>. See the description of that template and its methods for
977 * more information.
978 *
979 * Output GUID arrays are handled by a separate class, SafeGUIDArrayOut, since
980 * this class cannot handle them because of const modifiers.
981 */
982class SafeGUIDArray : public SafeArray <nsID *>
983{
984public:
985
986 typedef SafeArray <nsID *> Base;
987
988 class nsIDRef
989 {
990 public:
991
992 nsIDRef (nsID * &aVal) : mVal (aVal) {}
993
994 operator const nsID &() const { return mVal ? *mVal : *Empty; }
995 operator nsID() const { return mVal ? *mVal : *Empty; }
996
997 const nsID *operator&() const { return mVal ? mVal : Empty; }
998
999 nsIDRef &operator= (const nsID &aThat)
1000 {
1001 if (mVal == NULL)
1002 Copy (&aThat, mVal);
1003 else
1004 *mVal = aThat;
1005 return *this;
1006 }
1007
1008 private:
1009
1010 nsID * &mVal;
1011
1012 static const nsID *Empty;
1013
1014 friend class SafeGUIDArray;
1015 };
1016
1017 /** See SafeArray<>::SafeArray(). */
1018 SafeGUIDArray() {}
1019
1020 /** See SafeArray<>::SafeArray (size_t). */
1021 SafeGUIDArray (size_t aSize) : Base (aSize) {}
1022
1023 /**
1024 * Array access operator that returns an array element by reference. As a
1025 * special case, the return value of this operator on XPCOM is a nsID (GUID)
1026 * reference, instead of a nsID pointer (the actual SafeArray template
1027 * argument), for compatibility with the MS COM version.
1028 *
1029 * The rest is equivalent to SafeArray<>::operator[].
1030 */
1031 nsIDRef operator[] (size_t aIdx)
1032 {
1033 Assert (m.arr != NULL);
1034 Assert (aIdx < size());
1035 return nsIDRef (m.arr [aIdx]);
1036 }
1037
1038 /**
1039 * Const version of #operator[] that returns an array element by value.
1040 */
1041 const nsID &operator[] (size_t aIdx) const
1042 {
1043 Assert (m.arr != NULL);
1044 Assert (aIdx < size());
1045 return m.arr [aIdx] ? *m.arr [aIdx] : *nsIDRef::Empty;
1046 }
1047};
1048
1049/**
1050 * Version of com::SafeArray for const arrays of GUID.
1051 *
1052 * This class is used to work with input GUID array parameters in method
1053 * implementations. See SafeGUIDArray for more details.
1054 */
1055class SafeConstGUIDArray : public SafeArray <const nsID *,
1056 SafeArrayTraits <nsID *> >
1057{
1058public:
1059
1060 typedef SafeArray <const nsID *, SafeArrayTraits <nsID *> > Base;
1061
1062 /** See SafeArray<>::SafeArray(). */
1063 SafeConstGUIDArray() {}
1064
1065 /* See SafeArray<>::SafeArray (ComSafeArrayIn (T, aArg)). */
1066 SafeConstGUIDArray (ComSafeGUIDArrayIn (aArg))
1067 : Base (ComSafeGUIDArrayInArg (aArg)) {}
1068
1069 /**
1070 * Array access operator that returns an array element by reference. As a
1071 * special case, the return value of this operator on XPCOM is nsID (GUID)
1072 * instead of nsID *, for compatibility with the MS COM version.
1073 *
1074 * The rest is equivalent to SafeArray<>::operator[].
1075 */
1076 const nsID &operator[] (size_t aIdx) const
1077 {
1078 AssertReturn (m.arr != NULL, **((const nsID * *) NULL));
1079 AssertReturn (aIdx < size(), **((const nsID * *) NULL));
1080 return *m.arr [aIdx];
1081 }
1082
1083private:
1084
1085 /* These are disabled because of const */
1086 bool reset (size_t aNewSize) { NOREF (aNewSize); return false; }
1087};
1088
1089#else /* defined (VBOX_WITH_XPCOM) */
1090
1091typedef SafeArray <GUID> SafeGUIDArray;
1092typedef SafeArray <const GUID, SafeArrayTraits <GUID> > SafeConstGUIDArray;
1093
1094#endif /* defined (VBOX_WITH_XPCOM) */
1095
1096////////////////////////////////////////////////////////////////////////////////
1097
1098#if defined (VBOX_WITH_XPCOM)
1099
1100template <class I>
1101struct SafeIfaceArrayTraits
1102{
1103protected:
1104
1105 static void Init (I * &aElem) { aElem = NULL; }
1106 static void Uninit (I * &aElem)
1107 {
1108 if (aElem)
1109 {
1110 aElem->Release();
1111 aElem = NULL;
1112 }
1113 }
1114
1115 static void Copy (I * aFrom, I * &aTo)
1116 {
1117 if (aFrom != NULL)
1118 {
1119 aTo = aFrom;
1120 aTo->AddRef();
1121 }
1122 else
1123 aTo = NULL;
1124 }
1125
1126public:
1127
1128 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
1129 static I **__asInParam_Arr (I **aArr) { return aArr; }
1130 static I **__asInParam_Arr (const I **aArr) { return const_cast <I **> (aArr); }
1131};
1132
1133#else /* defined (VBOX_WITH_XPCOM) */
1134
1135template <class I>
1136struct SafeIfaceArrayTraits
1137{
1138protected:
1139
1140 static VARTYPE VarType() { return VT_UNKNOWN; }
1141 static ULONG VarCount (size_t aSize) { return (ULONG) aSize; }
1142 static size_t Size (ULONG aVarCount) { return (size_t) aVarCount; }
1143
1144 static void Copy (I * aFrom, I * &aTo)
1145 {
1146 if (aFrom != NULL)
1147 {
1148 aTo = aFrom;
1149 aTo->AddRef();
1150 }
1151 else
1152 aTo = NULL;
1153 }
1154};
1155
1156#endif /* defined (VBOX_WITH_XPCOM) */
1157
1158////////////////////////////////////////////////////////////////////////////////
1159
1160/**
1161 * Version of com::SafeArray for arrays of interface pointers.
1162 *
1163 * Except that it manages arrays of interface pointers, the usage of this class
1164 * is identical to com::SafeArray.
1165 *
1166 * @param I Interface class (no asterisk).
1167 */
1168template <class I>
1169class SafeIfaceArray : public SafeArray <I *, SafeIfaceArrayTraits <I> >
1170{
1171public:
1172
1173 typedef SafeArray <I *, SafeIfaceArrayTraits <I> > Base;
1174
1175 /**
1176 * Creates a null array.
1177 */
1178 SafeIfaceArray() {}
1179
1180 /**
1181 * Creates a new array of the given size. All elements of the newly created
1182 * array initialized with null values.
1183 *
1184 * @param aSize Initial number of elements in the array. Must be greater
1185 * than 0.
1186 *
1187 * @note If this object remains null after construction it means that there
1188 * was not enough memory for creating an array of the requested size.
1189 * The constructor will also assert in this case.
1190 */
1191 SafeIfaceArray (size_t aSize) { reset (aSize); }
1192
1193 /**
1194 * Weakly attaches this instance to the existing array passed in a method
1195 * parameter declared using the ComSafeArrayIn macro. When using this call,
1196 * always wrap the parameter name in the ComSafeArrayOutArg macro call like
1197 * this:
1198 * <pre>
1199 * SafeArray safeArray (ComSafeArrayInArg (aArg));
1200 * </pre>
1201 *
1202 * Note that this constructor doesn't take the ownership of the array. In
1203 * particular, it means that operations that operate on the ownership (e.g.
1204 * #detachTo()) are forbidden and will assert.
1205 *
1206 * @param aArg Input method parameter to attach to.
1207 */
1208 SafeIfaceArray (ComSafeArrayIn (I *, aArg))
1209 {
1210#if defined (VBOX_WITH_XPCOM)
1211
1212 AssertReturnVoid (aArg != NULL);
1213
1214 Base::m.size = aArgSize;
1215 Base::m.arr = aArg;
1216 Base::m.isWeak = true;
1217
1218#else /* defined (VBOX_WITH_XPCOM) */
1219
1220 AssertReturnVoid (aArg != NULL);
1221 SAFEARRAY *arg = *aArg;
1222
1223 if (arg)
1224 {
1225 AssertReturnVoid (arg->cDims == 1);
1226
1227 VARTYPE vt;
1228 HRESULT rc = SafeArrayGetVartype (arg, &vt);
1229 AssertComRCReturnVoid (rc);
1230 AssertMsgReturnVoid (vt == VT_UNKNOWN,
1231 ("Expected vartype VT_UNKNOWN, got %d.\n",
1232 VarType(), vt));
1233 GUID guid;
1234 rc = SafeArrayGetIID (arg, &guid);
1235 AssertComRCReturnVoid (rc);
1236 AssertMsgReturnVoid (InlineIsEqualGUID (_ATL_IIDOF (I), guid),
1237 ("Expected IID {%Vuuid}, got {%Vuuid}.\n",
1238 &_ATL_IIDOF (I), &guid));
1239 }
1240
1241 m.arr = arg;
1242 m.isWeak = true;
1243
1244 AssertReturnVoid (accessRaw() != NULL);
1245
1246#endif /* defined (VBOX_WITH_XPCOM) */
1247 }
1248
1249 /**
1250 * Creates a deep copy of the given standard C++ container that stores
1251 * interface pointers as objects of the ComPtr <I> class.
1252 *
1253 * @param aCntr Container object to copy.
1254 *
1255 * @param C Standard C++ container template class (normally deduced from
1256 * @c aCntr).
1257 * @param A Standard C++ allocator class (deduced from @c aCntr).
1258 * @param OI Argument to the ComPtr template (deduced from @c aCntr).
1259 */
1260 template <template <typename, typename> class C, class A, class OI>
1261 SafeIfaceArray (const C <ComPtr <OI>, A> & aCntr)
1262 {
1263 typedef C <ComPtr <OI>, A> List;
1264
1265 reset (aCntr.size());
1266 AssertReturnVoid (!Base::isNull());
1267
1268 int i = 0;
1269 for (typename List::const_iterator it = aCntr.begin();
1270 it != aCntr.end(); ++ it, ++ i)
1271#if defined (VBOX_WITH_XPCOM)
1272 Copy (*it, Base::m.arr [i]);
1273#else
1274 Copy (*it, Base::m.raw [i]);
1275#endif
1276 }
1277
1278 /**
1279 * Creates a deep copy of the given standard C++ container that stores
1280 * interface pointers as objects of the ComObjPtr <I> class.
1281 *
1282 * @param aCntr Container object to copy.
1283 *
1284 * @param C Standard C++ container template class (normally deduced from
1285 * @c aCntr).
1286 * @param A Standard C++ allocator class (deduced from @c aCntr).
1287 * @param OI Argument to the ComObjPtr template (deduced from @c aCntr).
1288 */
1289 template <template <typename, typename> class C, class A, class OI>
1290 SafeIfaceArray (const C <ComObjPtr <OI>, A> & aCntr)
1291 {
1292 typedef C <ComObjPtr <OI>, A> List;
1293
1294 reset (aCntr.size());
1295 AssertReturnVoid (!Base::isNull());
1296
1297 int i = 0;
1298 for (typename List::const_iterator it = aCntr.begin();
1299 it != aCntr.end(); ++ it, ++ i)
1300#if defined (VBOX_WITH_XPCOM)
1301 Copy (*it, Base::m.arr [i]);
1302#else
1303 Copy (*it, Base::m.raw [i]);
1304#endif
1305 }
1306
1307 /**
1308 * Reinitializes this instance by preallocating space for the given number
1309 * of elements. The previous array contents is lost.
1310 *
1311 * @param aNewSize New number of elements in the array.
1312 * @return @c true on success and false if there is not enough
1313 * memory for resizing.
1314 */
1315 virtual bool reset (size_t aNewSize)
1316 {
1317 Base::m.uninit();
1318
1319#if defined (VBOX_WITH_XPCOM)
1320
1321 /* Note: for zero-sized arrays, we use the size of 1 because whether
1322 * malloc(0) returns a null pointer or not (which is used in isNull())
1323 * is implementation-dependent according to the C standard. */
1324
1325 Base::m.arr = (I **) nsMemory::Alloc (RT_MAX (aNewSize, 1) * sizeof (I *));
1326 AssertReturn (Base::m.arr != NULL, false);
1327
1328 Base::m.size = aNewSize;
1329
1330 for (size_t i = 0; i < Base::m.size; ++ i)
1331 Init (Base::m.arr [i]);
1332
1333#else
1334
1335 SAFEARRAYBOUND bound = { (ULONG)aNewSize, 0 };
1336 m.arr = SafeArrayCreateEx (VT_UNKNOWN, 1, &bound,
1337 (PVOID) &_ATL_IIDOF (I));
1338 AssertReturn (m.arr != NULL, false);
1339
1340 AssertReturn (accessRaw() != NULL, false);
1341
1342#endif
1343 return true;
1344 }
1345};
1346
1347} /* namespace com */
1348
1349/** @} */
1350
1351#endif /* ___VBox_com_array_h */
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