Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ Generated `IReference<T>` values use `T | null` in JavaScript. Native values,
The same projection applies when `IReference<T>` appears inside a WinRT struct;
packing boxes the field automatically and unpacking returns the native value.

Generated `Windows.Storage.Streams.Buffer` and `IBuffer` projections provide
copied byte conversion. `fromBuffer()` accepts a Node.js `Buffer` or
`Uint8Array`, and `toBuffer()` returns a new `Buffer` containing exactly
`Length` bytes:

```js
const winrtBuffer = IBuffer.fromBuffer(Buffer.from([0, 1, 255]))
const bytes = winrtBuffer.toBuffer()
```

Both directions copy. Mutating the input or releasing the WinRT object does not
change the returned bytes, and no native buffer pointer is exposed.

Generated packages export `createProjectedLifetimeScope()`. WinUI/XAML hosts
can create a scope after Application and Window setup, then dispose it before
the native window and XAML core are destroyed. Active scopes retain projected
Expand Down
20 changes: 20 additions & 0 deletions bindings/js/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,26 @@ test('release WinRT object values deterministically', (t) => {
t.notThrows(() => value.release())
})

test('copy between WinRT IBuffer and Buffer or Uint8Array', (t) => {
const empty = DynWinRtValue.fromBuffer(Buffer.alloc(0))
t.deepEqual(empty.toBuffer(), Buffer.alloc(0))

const input = Uint8Array.from([0, 1, 2, 0, 255, 128])
const value = DynWinRtValue.fromBuffer(input)
input.fill(9)
const copy = value.toBuffer()
value.release()

t.true(Buffer.isBuffer(copy))
t.deepEqual(copy, Buffer.from([0, 1, 2, 0, 255, 128]))
t.throws(() => DynWinRtValue.u8Value(1).toBuffer(), {
message: /Expected a Windows\.Storage\.Streams\.IBuffer/,
})
t.throws(() => DynWinRtValue.activationFactory('Windows.Foundation.Uri').toBuffer(), {
message: /80004002|No such interface/i,
})
})

test('round-trip WinRT value arrays', (t) => {
const array = DynWinRtArray.fromI32Values([1, 2, 3])
t.is(array.len(), 3)
Expand Down
18 changes: 18 additions & 0 deletions bindings/js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,16 @@ impl DynWinRTValue {
Ok(DynWinRTValue::new(factory))
}

/// Create an owned WinRT IBuffer by copying a Node.js Buffer or Uint8Array.
#[napi]
pub fn from_buffer(
#[napi(ts_arg_type = "Buffer | Uint8Array")] data: napi::bindgen_prelude::Uint8Array,
) -> napi::Result<DynWinRTValue> {
dynwinrt::copy_to_ibuffer(&data)
.map(DynWinRTValue::new)
.map_err(|error| napi::Error::from_reason(error.message()))
}

/// Create a composed WinUI Application that forwards IXamlMetadataProvider
/// calls to the supplied provider.
#[napi]
Expand Down Expand Up @@ -1533,6 +1543,14 @@ impl DynWinRTValue {
}
}

/// Copy the initialized bytes from a WinRT IBuffer into a Node.js Buffer.
#[napi]
pub fn to_buffer(&self) -> napi::Result<napi::bindgen_prelude::Buffer> {
dynwinrt::copy_from_ibuffer(&self.0)
.map(Into::into)
.map_err(|error| napi::Error::from_reason(error.message()))
}

#[napi]
pub fn is_null(&self) -> bool {
self.3.is_none() && self.4.is_none() && self.5.is_none() && self.0.is_null_object()
Expand Down
12 changes: 12 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ WinRT collection interfaces. Byte arrays accept `bytes` and `bytearray`; GUID,
`DateTime`, and `TimeSpan` values use `uuid.UUID`, `datetime.datetime`, and
`datetime.timedelta`.

Generated `Windows.Storage.Streams.Buffer` and `IBuffer` projections also
provide copied byte conversion:

```python
winrt_buffer = IBuffer.from_bytes(bytearray(b"\x00\x01\xff"))
data: bytes = winrt_buffer.to_bytes()
```

Both directions copy exactly `Length` bytes. Mutating the input or releasing
the WinRT object does not change the returned `bytes`, and no native buffer
pointer is exposed.

Exceptions raised by Python event or delegate callbacks are reported through
`sys.unraisablehook`. The originating WinRT invocation receives
`0xA0EE4005` (`PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION`) instead of unconditional
Expand Down
3 changes: 3 additions & 0 deletions bindings/py/dynwinrt.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ class DynWinRTValue:
@staticmethod
def activation_factory(name: str) -> DynWinRTValue: ...
@staticmethod
def from_bytes(data: Union[bytes, bytearray]) -> DynWinRTValue: ...
@staticmethod
def create_xaml_application(
metadata_provider: DynWinRTValue,
launched_callback: Optional[DynWinRTValue] = ...,
Expand Down Expand Up @@ -322,6 +324,7 @@ class DynWinRTValue:
def to_u64(self) -> int: ...
def to_f64(self) -> float: ...
def to_guid(self) -> WinGUID: ...
def to_bytes(self) -> bytes: ...
def is_null(self) -> bool: ...
def release(self) -> None: ...
def as_raw(self) -> int: ...
Expand Down
24 changes: 24 additions & 0 deletions bindings/py/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,23 @@ impl DynWinRTValue {
.map_err(map_dynwinrt_error)
}

/// Create an owned WinRT IBuffer by copying Python bytes or bytearray data.
#[staticmethod]
fn from_bytes(data: &Bound<'_, PyAny>) -> PyResult<DynWinRTValue> {
let bytes = if let Ok(data) = data.cast::<pyo3::types::PyBytes>() {
data.as_bytes().to_vec()
} else if let Ok(data) = data.cast::<pyo3::types::PyByteArray>() {
data.to_vec()
} else {
return Err(pyo3::exceptions::PyTypeError::new_err(
"from_bytes: expected bytes or bytearray",
));
};
dynwinrt::copy_to_ibuffer(&bytes)
.map(DynWinRTValue)
.map_err(map_dynwinrt_error)
}

/// Compose a WinUI `Microsoft.UI.Xaml.Application` whose outer object
/// exposes the supplied `IXamlMetadataProvider`.
///
Expand Down Expand Up @@ -1440,6 +1457,13 @@ impl DynWinRTValue {
}
}

/// Copy the initialized bytes from a WinRT IBuffer into Python bytes.
fn to_bytes<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PyBytes>> {
dynwinrt::copy_from_ibuffer(&self.0)
.map(|bytes| pyo3::types::PyBytes::new(py, &bytes))
.map_err(map_dynwinrt_error)
}

fn is_null(&self) -> bool {
self.0.is_null_object()
}
Expand Down
25 changes: 25 additions & 0 deletions bindings/py/tests/test_phase1.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* WinRTAsync — public asyncio-compatible protocols
* DynWinRTArray.to_bytes/from_bytes — Pythonic byte-buffer interop
* DynWinRTArray.from_object_values — T[] of object/interface elements
* DynWinRTValue.to_bytes/from_bytes — copied IBuffer interop
"""

import asyncio
Expand Down Expand Up @@ -1066,6 +1067,30 @@ def test_from_bytes_accepts_bytearray():
assert arr.to_bytes() == bytes(data)


def test_ibuffer_bytes_round_trip_and_copy_isolation():
empty = DynWinRTValue.from_bytes(b"")
assert empty.to_bytes() == b""

data = bytearray(b"\x00\x01\x02\x00\xff\x80")
value = DynWinRTValue.from_bytes(data)
data[:] = b"\x09" * len(data)
copied = value.to_bytes()
value.release()

assert isinstance(copied, bytes)
assert copied == b"\x00\x01\x02\x00\xff\x80"


def test_ibuffer_bytes_rejects_unsupported_values():
with pytest.raises(RuntimeError, match="Windows.Storage.Streams.IBuffer"):
DynWinRTValue.from_u8(1).to_bytes()

uri_factory = DynWinRTValue.activation_factory("Windows.Foundation.Uri")
with pytest.raises(OSError) as exc_info:
uri_factory.to_bytes()
assert exc_info.value.winerror == -2147467262 # E_NOINTERFACE


def test_winrt_datetime_round_trip():
value = datetime(2024, 1, 2, 3, 4, 5, 678901, tzinfo=timezone.utc)
assert _dynwinrt_ticks_to_datetime(_dynwinrt_datetime_to_ticks(value)) == value
Expand Down
Loading
Loading