wincom 0.3.0

A lightweight Rust wrapper for Windows COM IDispatch automation, providing RAII VARIANT management and simplified property/method invocation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! RAII `VARIANT` wrapper and Rust type conversions.
//!
//! # Why a wrapper?
//!
//! `windows-rs` exposes `VARIANT` as a plain `#[repr(C)]` struct with no
//! `Drop` implementation. Every value that owns heap-allocated data
//! (`BSTR`, `SAFEARRAY`, `IDispatch`, `IUnknown`) must be cleaned up with
//! `VariantClear`. Forgetting to do so leaks — a common bug in COM code.
//!
//! [`Variant`] wraps `VARIANT` and calls `VariantClear` in its `Drop`
//! impl. Use it everywhere you would otherwise use a raw `VARIANT`.
//!
//! # Constructing
//!
//! ```
//! use wincom::Variant;
//!
//! let i = Variant::from_i32(42);
//! let s = Variant::from_str("hello");
//! let b = Variant::from_bool(true);
//! let arr = Variant::from_vec_f64(&[1.0, 2.0, 3.0])?;
//! # Ok::<(), wincom::Error>(())
//! ```
//!
//! # Converting back
//!
//! Every `to_*` method uses `VariantChangeType` internally, so a value
//! stored as `VT_I4` can be read as `i64`, `f64`, or `String` without
//! manual conversion:
//!
//! ```
//! # use wincom::Variant;
//! # fn example() -> wincom::Result<()> {
//! let v = Variant::from_i32(42);
//! assert_eq!(v.to_i64()?,  42_i64);
//! assert_eq!(v.to_f64()?,  42.0_f64);
//! assert_eq!(v.to_string()?, "42");
//! # Ok(())
//! # }
//! ```
//!
//! Conversion failures preserve the underlying `HRESULT` in
//! [`Error::Windows`](crate::Error::Windows).
//!
//! # `byref_of`
//!
//! [`Variant::byref_of`] constructs a `VT_BYREF | VT_VARIANT` that points
//! at another `Variant`. The result is only valid for the lifetime of the
//! referenced variant, and only for the duration of a single COM call. Do
//! not store it. The
//! [`ComObject::invoke_method_inout`](crate::ComObject::invoke_method_inout)
//! helper handles this correctly; prefer it over calling `byref_of`
//! directly.

use std::ffi::c_void;
use std::mem::ManuallyDrop;

use windows::core::BSTR;
use windows::Win32::Foundation::{E_OUTOFMEMORY, VARIANT_BOOL};
use windows::Win32::System::Com::IDispatch;
use windows::Win32::System::Ole;
use windows::Win32::System::Variant::{
    VariantChangeType, VariantClear, VariantGetElementCount, VARENUM, VAR_CHANGE_FLAGS,
    VARIANT, VARIANT_0_0, VT_ARRAY, VT_BOOL, VT_BSTR, VT_BYREF, VT_DISPATCH, VT_EMPTY, VT_I2,
    VT_I4, VT_I8, VT_NULL, VT_R8, VT_UI1, VT_UI2, VT_UI4, VT_UI8, VT_VARIANT,
};

use crate::err::{Error, Result};

/// Internal helper: build an error for a failed `SafeArrayCreateVector`.
fn safearray_alloc_failed() -> Error {
    Error::Windows(windows::core::Error::new(
        E_OUTOFMEMORY,
        "SafeArrayCreateVector failed",
    ))
}

/// RAII wrapper over `VARIANT`.
///
/// Calls `VariantClear` on drop, ensuring that `BSTR`, `SAFEARRAY`, and
/// interface pointers are released exactly once. See the [module
/// documentation](self) for construction and conversion examples.
///
/// # Layout
///
/// `Variant` is `#[repr(transparent)]` over `VARIANT`, so `&Variant` can
/// be passed wherever a `*const VARIANT` is expected. Use
/// [`Variant::as_raw`] / [`Variant::as_raw_mut`] for explicit conversions.
///
/// # Ownership
///
/// `Variant` owns its contents. It is intentionally **not** `Clone`,
/// because cloning a `VARIANT` requires `VariantCopy` and the cost is
/// non-obvious. If you need a copy, do it explicitly:
///
/// ```
/// # use wincom::Variant;
/// # fn example(v: &Variant) -> wincom::Result<()> {
/// let copy = Variant::from_str(v.to_string()?);
/// # let _ = copy;
/// # Ok(())
/// # }
/// ```
#[repr(transparent)]
pub struct Variant(pub VARIANT);

impl Default for Variant {
    fn default() -> Self {
        Self::empty()
    }
}

impl Drop for Variant {
    fn drop(&mut self) {
        unsafe {
            // Even if cleanup fails, we must not panic in Drop.
            let _ = VariantClear(&mut self.0);
        }
    }
}

impl std::ops::Deref for Variant {
    type Target = VARIANT;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for Variant {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl From<VARIANT> for Variant {
    /// Takes ownership of a raw `VARIANT`. The caller must **not** clear
    /// it afterwards.
    fn from(v: VARIANT) -> Self {
        Self(v)
    }
}

impl Variant {
    // ---------- Constructors ----------

    /// Creates an empty `VT_EMPTY` variant.
    ///
    /// This is equivalent to `VARIANT::default()` in `windows-rs`.
    pub fn empty() -> Self {
        Self(VARIANT::default())
    }

    /// Creates a `VT_NULL` variant (SQL-style null).
    ///
    /// Distinct from [`Self::empty`]: `VT_NULL` is an explicit null value,
    /// while `VT_EMPTY` means "unset".
    pub fn null() -> Self {
        let mut v = VARIANT::default();
        let v00 = VARIANT_0_0 {
            vt: VT_NULL,
            ..Default::default()
        };
        v.Anonymous.Anonymous = ManuallyDrop::new(v00);
        Self(v)
    }

    /// Constructs a `VT_I2` variant from an `i16`.
    pub fn from_i16(n: i16) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_I2, ..Default::default() };
        v00.Anonymous.iVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_I4` variant from an `i32`.
    pub fn from_i32(n: i32) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_I4, ..Default::default() };
        v00.Anonymous.lVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_I8` variant from an `i64`.
    pub fn from_i64(n: i64) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_I8, ..Default::default() };
        v00.Anonymous.llVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_UI1` variant from a `u8`.
    pub fn from_u8(n: u8) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_UI1, ..Default::default() };
        v00.Anonymous.bVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_UI2` variant from a `u16`.
    pub fn from_u16(n: u16) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_UI2, ..Default::default() };
        v00.Anonymous.uiVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_UI4` variant from a `u32`.
    pub fn from_u32(n: u32) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_UI4, ..Default::default() };
        v00.Anonymous.ulVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_UI8` variant from a `u64`.
    pub fn from_u64(n: u64) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_UI8, ..Default::default() };
        v00.Anonymous.ullVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_R8` variant from an `f64`.
    pub fn from_f64(n: f64) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_R8, ..Default::default() };
        v00.Anonymous.dblVal = n;
        Self::from_v00(v00)
    }

    /// Constructs a `VT_BOOL` variant from a `bool`.
    pub fn from_bool(b: bool) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_BOOL, ..Default::default() };
        v00.Anonymous.boolVal = VARIANT_BOOL::from(b);
        Self::from_v00(v00)
    }

    /// Constructs a `VT_BSTR` variant from a string.
    ///
    /// The string is copied into a `BSTR` (wide, length-prefixed). The
    /// BSTR is released on drop.
    pub fn from_str<S: AsRef<str>>(s: S) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_BSTR, ..Default::default() };
        v00.Anonymous.bstrVal = ManuallyDrop::new(BSTR::from(s.as_ref()));
        Self::from_v00(v00)
    }

    /// Constructs a `VT_ARRAY | VT_R8` SAFEARRAY variant from a slice of
    /// `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Windows`] with `E_OUTOFMEMORY` if the underlying
    /// `SafeArrayCreateVector` fails.
    pub fn from_vec_f64(arr: &[f64]) -> Result<Self> {
        unsafe {
            let psa = Ole::SafeArrayCreateVector(VT_R8, 0, arr.len() as u32);
            if psa.is_null() {
                return Err(safearray_alloc_failed());
            }
            for (i, &value) in arr.iter().enumerate() {
                let idx = i as i32;
                Ole::SafeArrayPutElement(psa, &idx, &value as *const _ as *const c_void)?;
            }
            let mut v00 = VARIANT_0_0 {
                vt: VARENUM(VT_ARRAY.0 | VT_R8.0),
                ..Default::default()
            };
            v00.Anonymous.parray = psa;
            Ok(Self::from_v00(v00))
        }
    }

    /// Constructs a `VT_ARRAY | VT_I8` SAFEARRAY variant from a slice of
    /// `i64`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::from_vec_f64`].
    pub fn from_vec_i64(arr: &[i64]) -> Result<Self> {
        unsafe {
            let psa = Ole::SafeArrayCreateVector(VT_I8, 0, arr.len() as u32);
            if psa.is_null() {
                return Err(safearray_alloc_failed());
            }
            for (i, &value) in arr.iter().enumerate() {
                let idx = i as i32;
                Ole::SafeArrayPutElement(psa, &idx, &value as *const _ as *const c_void)?;
            }
            let mut v00 = VARIANT_0_0 {
                vt: VARENUM(VT_ARRAY.0 | VT_I8.0),
                ..Default::default()
            };
            v00.Anonymous.parray = psa;
            Ok(Self::from_v00(v00))
        }
    }

    /// Constructs an empty `VT_ARRAY | VT_R8` SAFEARRAY of the given
    /// length.
    ///
    /// # Errors
    ///
    /// Same as [`Self::from_vec_f64`].
    pub fn empty_f64_array(len: u32) -> Result<Self> {
        unsafe {
            let psa = Ole::SafeArrayCreateVector(VT_R8, 0, len);
            if psa.is_null() {
                return Err(safearray_alloc_failed());
            }
            let mut v00 = VARIANT_0_0 {
                vt: VARENUM(VT_ARRAY.0 | VT_R8.0),
                ..Default::default()
            };
            v00.Anonymous.parray = psa;
            Ok(Self::from_v00(v00))
        }
    }

    /// Constructs a `VT_DISPATCH` variant that owns a reference to
    /// `disp`.
    ///
    /// This calls `IDispatch::AddRef` via `IDispatch::clone`; the
    /// reference is released when the `Variant` is dropped.
    pub fn from_dispatch(disp: &IDispatch) -> Self {
        let mut v00 = VARIANT_0_0 { vt: VT_DISPATCH, ..Default::default() };
        v00.Anonymous.pdispVal = ManuallyDrop::new(Some(disp.clone()));
        Self::from_v00(v00)
    }

    /// Takes ownership of a raw `VARIANT`.
    ///
    /// After this call the caller must not use `v` and must not call
    /// `VariantClear` on it.
    pub fn from_raw(v: VARIANT) -> Self {
        Self(v)
    }

    /// Releases ownership, returning a raw `VARIANT` that the caller is
    /// responsible for clearing.
    ///
    /// This is the inverse of [`Self::from_raw`].
    pub fn into_raw(self) -> VARIANT {
        let v = unsafe { std::ptr::read(&self.0) };
        std::mem::forget(self);
        v
    }

    /// Borrows the inner `VARIANT`.
    pub fn as_raw(&self) -> &VARIANT {
        &self.0
    }

    /// Mutably borrows the inner `VARIANT`.
    pub fn as_raw_mut(&mut self) -> &mut VARIANT {
        &mut self.0
    }

    /// Internal: assemble a `VARIANT` from a prepared `VARIANT_0_0`.
    fn from_v00(v00: VARIANT_0_0) -> Self {
        let mut v = VARIANT::default();
        v.Anonymous.Anonymous = ManuallyDrop::new(v00);
        Self(v)
    }

    // ---------- Inspection ----------

    /// Returns the underlying `VARENUM` (`vt`).
    pub fn vt(&self) -> VARENUM {
        unsafe { self.0.Anonymous.Anonymous.vt }
    }

    /// Returns `true` if the variant is `VT_NULL` or `VT_EMPTY`.
    pub fn is_null(&self) -> bool {
        matches!(self.vt(), VT_NULL | VT_EMPTY)
    }

    /// Returns `true` if the variant is `VT_EMPTY` (unset).
    pub fn is_empty(&self) -> bool {
        self.vt() == VT_EMPTY
    }

    // ---------- Numeric conversions ----------

    /// Converts to `i16` via `VariantChangeType(..., VT_I2)`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Windows`] if the conversion is not possible
    /// (`DISP_E_TYPEMISMATCH`, `DISP_E_OVERFLOW`, …).
    pub fn to_i16(&self) -> Result<i16> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_I2)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.iVal)
        }
    }

    /// Converts to `i32` via `VariantChangeType(..., VT_I4)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_i32(&self) -> Result<i32> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_I4)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.lVal)
        }
    }

    /// Converts to `i64` via `VariantChangeType(..., VT_I8)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_i64(&self) -> Result<i64> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_I8)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.llVal)
        }
    }

    /// Converts to `u8` via `VariantChangeType(..., VT_UI1)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_u8(&self) -> Result<u8> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_UI1)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.bVal)
        }
    }

    /// Converts to `u16` via `VariantChangeType(..., VT_UI2)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_u16(&self) -> Result<u16> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_UI2)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.uiVal)
        }
    }

    /// Converts to `u32` via `VariantChangeType(..., VT_UI4)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_u32(&self) -> Result<u32> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_UI4)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.ulVal)
        }
    }

    /// Converts to `u64` via `VariantChangeType(..., VT_UI8)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_u64(&self) -> Result<u64> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_UI8)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.ullVal)
        }
    }

    /// Converts to `f64` via `VariantChangeType(..., VT_R8)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_f64(&self) -> Result<f64> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_R8)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.dblVal)
        }
    }

    /// Converts to `bool` via `VariantChangeType(..., VT_BOOL)`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_bool(&self) -> Result<bool> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_BOOL)?;
            let new = Variant::from_raw(new);
            Ok(new.0.Anonymous.Anonymous.Anonymous.boolVal.as_bool())
        }
    }

    /// Converts to `String` via `VariantChangeType(..., VT_BSTR)`.
    ///
    /// Numeric and boolean variants are formatted into a BSTR first.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_i16`].
    pub fn to_string(&self) -> Result<String> {
        unsafe {
            let mut new = VARIANT::default();
            VariantChangeType(&mut new, &self.0, VAR_CHANGE_FLAGS(0), VT_BSTR)?;
            let new = Variant::from_raw(new);
            let bstr: &BSTR = &new.0.Anonymous.Anonymous.Anonymous.bstrVal;
            Ok(bstr.to_string())
        }
    }

    // ---------- SAFEARRAY reads ----------

    /// Internal: number of elements in the underlying SAFEARRAY.
    unsafe fn elem_count(&self) -> i32 {
        VariantGetElementCount(&self.0) as i32
    }

    /// Reads a `VT_ARRAY | VT_R8` variant as `Vec<f64>`.
    ///
    /// Returns an empty vector for a null array pointer.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Windows`] if `SafeArrayGetElement` fails (usually
    /// a type mismatch).
    pub fn to_f64_array(&self) -> Result<Vec<f64>> {
        unsafe {
            let psa = self.0.Anonymous.Anonymous.Anonymous.parray;
            if psa.is_null() {
                return Ok(Vec::new());
            }
            let count = self.elem_count();
            let mut out = Vec::with_capacity(count as usize);
            for i in 0..count {
                let mut value: f64 = 0.0;
                Ole::SafeArrayGetElement(psa, &i, &mut value as *mut _ as *mut c_void)?;
                out.push(value);
            }
            Ok(out)
        }
    }

    /// Alias for [`Self::to_f64_array`] kept for backward compatibility.
    pub fn to_double_array(&self) -> Result<Vec<f64>> {
        self.to_f64_array()
    }

    /// Reads a `VT_ARRAY | VT_I8` variant as `Vec<i64>`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_f64_array`].
    pub fn to_i64_array(&self) -> Result<Vec<i64>> {
        unsafe {
            let psa = self.0.Anonymous.Anonymous.Anonymous.parray;
            if psa.is_null() {
                return Ok(Vec::new());
            }
            let count = self.elem_count();
            let mut out = Vec::with_capacity(count as usize);
            for i in 0..count {
                let mut value: i64 = 0;
                Ole::SafeArrayGetElement(psa, &i, &mut value as *mut _ as *mut c_void)?;
                out.push(value);
            }
            Ok(out)
        }
    }

    /// Reads a `VT_ARRAY | VT_BSTR` variant as `Vec<String>`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_f64_array`].
    pub fn to_string_array(&self) -> Result<Vec<String>> {
        unsafe {
            let psa = self.0.Anonymous.Anonymous.Anonymous.parray;
            if psa.is_null() {
                return Ok(Vec::new());
            }
            let count = self.elem_count();
            let mut out = Vec::with_capacity(count as usize);
            for i in 0..count {
                let mut bstr = BSTR::new();
                Ole::SafeArrayGetElement(psa, &i, &mut bstr as *mut _ as *mut c_void)?;
                out.push(bstr.to_string());
            }
            Ok(out)
        }
    }

    /// Reads a `VT_ARRAY | VT_VARIANT` variant as `Vec<Variant>`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_f64_array`].
    pub fn to_variant_array(&self) -> Result<Vec<Variant>> {
        unsafe {
            let psa = self.0.Anonymous.Anonymous.Anonymous.parray;
            if psa.is_null() {
                return Ok(Vec::new());
            }
            let count = self.elem_count();
            let mut out = Vec::with_capacity(count as usize);
            for i in 0..count {
                let mut elem = Variant::empty();
                Ole::SafeArrayGetElement(
                    psa,
                    &i,
                    elem.as_raw_mut() as *mut VARIANT as *mut c_void,
                )?;
                out.push(elem);
            }
            Ok(out)
        }
    }

    // ---------- IDispatch access ----------

    /// Returns a clone of the contained `IDispatch` (`AddRef`'d).
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoDispatch`] if the variant is not `VT_DISPATCH`
    /// or the pointer is null.
    pub fn to_idispatch(&self) -> Result<IDispatch> {
        unsafe {
            let opt: &Option<IDispatch> = &self.0.Anonymous.Anonymous.Anonymous.pdispVal;
            opt.as_ref().cloned().ok_or(Error::NoDispatch)
        }
    }

    /// Borrows the contained `IDispatch` without increasing its refcount.
    ///
    /// # Errors
    ///
    /// Same as [`Self::to_idispatch`].
    pub fn as_idispatch(&self) -> Result<&IDispatch> {
        unsafe {
            let opt: &Option<IDispatch> = &self.0.Anonymous.Anonymous.Anonymous.pdispVal;
            opt.as_ref().ok_or(Error::NoDispatch)
        }
    }

    // ---------- byref helper ----------

    /// Builds a `VT_BYREF | VT_VARIANT` variant pointing at `target`.
    ///
    /// # Safety
    ///
    /// The returned `Variant` holds a raw pointer to `target`. It is only
    /// valid for the lifetime of `target` and only for the duration of a
    /// single synchronous COM call. Do not store it.
    ///
    /// Prefer [`ComObject::invoke_method_inout`](crate::ComObject::invoke_method_inout)
    /// which manages the lifetime automatically.
    pub(crate) fn byref_of(target: &mut Variant) -> Variant {
        let mut v00 = VARIANT_0_0 {
            vt: VARENUM(VT_BYREF.0 | VT_VARIANT.0),
            ..Default::default()
        };
        v00.Anonymous.byref = target.as_raw_mut() as *mut VARIANT as *mut c_void;
        Self::from_v00(v00)
    }
}

// ---------- Compatibility: `VariantExt` for raw VARIANT ----------

/// Legacy extension trait providing constructors on raw `VARIANT`.
///
/// These methods return a raw `VARIANT` (not a [`Variant`]). **Use them
/// only for value types without heap allocation.** For BSTR, SAFEARRAY,
/// or IDispatch variants, use [`Variant`]'s associated functions instead
/// so the resource is cleaned up automatically.
pub trait VariantExt {
    /// Creates a `VT_NULL` variant.
    fn null() -> VARIANT;
    /// Creates a `VT_I2` variant.
    fn from_i16(n: i16) -> VARIANT;
    /// Creates a `VT_I4` variant.
    fn from_i32(n: i32) -> VARIANT;
    /// Creates a `VT_I8` variant.
    fn from_i64(n: i64) -> VARIANT;
    /// Creates a `VT_UI1` variant.
    fn from_u8(n: u8) -> VARIANT;
    /// Creates a `VT_UI2` variant.
    fn from_u16(n: u16) -> VARIANT;
    /// Creates a `VT_UI4` variant.
    fn from_u32(n: u32) -> VARIANT;
    /// Creates a `VT_UI8` variant.
    fn from_u64(n: u64) -> VARIANT;
    /// Creates a `VT_R8` variant.
    fn from_f64(n: f64) -> VARIANT;
    /// Creates a `VT_BOOL` variant.
    fn from_bool(b: bool) -> VARIANT;
    /// Creates a `VT_BSTR` variant.
    ///
    /// **Warning**: the returned `VARIANT` must be cleared by the caller
    /// (via `VariantClear`) to avoid a BSTR leak. Prefer
    /// [`Variant::from_str`].
    fn from_str<S: AsRef<str>>(s: S) -> VARIANT;
}

impl VariantExt for VARIANT {
    fn null() -> VARIANT {
        Variant::null().into_raw()
    }
    fn from_i16(n: i16) -> VARIANT { Variant::from_i16(n).into_raw() }
    fn from_i32(n: i32) -> VARIANT { Variant::from_i32(n).into_raw() }
    fn from_i64(n: i64) -> VARIANT { Variant::from_i64(n).into_raw() }
    fn from_u8(n: u8)   -> VARIANT { Variant::from_u8(n).into_raw() }
    fn from_u16(n: u16) -> VARIANT { Variant::from_u16(n).into_raw() }
    fn from_u32(n: u32) -> VARIANT { Variant::from_u32(n).into_raw() }
    fn from_u64(n: u64) -> VARIANT { Variant::from_u64(n).into_raw() }
    fn from_f64(n: f64) -> VARIANT { Variant::from_f64(n).into_raw() }
    fn from_bool(b: bool) -> VARIANT { Variant::from_bool(b).into_raw() }
    fn from_str<S: AsRef<str>>(s: S) -> VARIANT {
        Variant::from_str(s).into_raw()
    }
}