Skip to content

Commit a733e34

Browse files
authored
cxx-qt-lib: harden conversion of QObjectMutPtr from / to raw pointer. (#1486)
Replace `From` trait implementations with dedicated conversion methods to make raw pointer conversions a bit more explicit.
1 parent 91526d9 commit a733e34

2 files changed

Lines changed: 27 additions & 10 deletions

File tree

crates/cxx-qt-lib/include/core/qobjectmutptr.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@
99
#include <QtCore/QObject>
1010

1111
// Mirrors the Rust
12-
// `#[repr(transparent)] struct QObjectMutPtr(pub *mut QObject)`
12+
// `#[repr(transparent)] struct QObjectMutPtr(*mut QObject)`
1313
// so it can be used as a shared type across the bridge.
1414
using QObjectMutPtr = ::QObject*;

crates/cxx-qt-lib/src/core/qobjectmutptr.rs

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,37 @@ use cxx_qt::QObject;
77

88
/// A thin wrapper around `*mut QObject`.
99
/// Using the 'newtype' idiom lets us implement `ExternType`
10-
/// for it, which wouldn't possible for pure `*mut QObject` itself.
10+
/// for it, which wouldn't be possible for pure `*mut QObject` itself.
1111
#[repr(transparent)]
1212
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13-
pub struct QObjectMutPtr(pub *mut QObject);
13+
pub struct QObjectMutPtr(*mut QObject);
1414

15-
impl From<*mut QObject> for QObjectMutPtr {
16-
fn from(value: *mut QObject) -> Self {
17-
QObjectMutPtr(value)
15+
impl QObjectMutPtr {
16+
/// Create a new instance from a raw pointer.
17+
///
18+
/// # Safety
19+
///
20+
/// The pointer is passed to C++ as a `QObject*` and may be dereferenced
21+
/// there. This wrapper tracks neither ownership nor lifetime,
22+
/// so the object must outlive every use of the underlying QObject pointer
23+
/// (including any copy stored in a `QVariant` or `QList`).
24+
pub unsafe fn from_raw(raw: *mut QObject) -> Self {
25+
Self(raw)
26+
}
27+
28+
/// Return a wrapped raw const pointer.
29+
pub fn as_ptr(&self) -> *const QObject {
30+
self.0
31+
}
32+
33+
/// Return a wrapped raw mut pointer.
34+
pub fn as_mut_ptr(&self) -> *mut QObject {
35+
self.0
1836
}
19-
}
2037

21-
impl From<QObjectMutPtr> for *mut QObject {
22-
fn from(value: QObjectMutPtr) -> Self {
23-
value.0
38+
/// Consume an object a return a wrapped raw mut pointer.
39+
pub fn into_raw(self) -> *mut QObject {
40+
self.0
2441
}
2542
}
2643

0 commit comments

Comments
 (0)