opencv/manual/core/
ptr.rs

1use std::ffi::c_void;
2use std::marker::PhantomData;
3use std::mem::ManuallyDrop;
4
5pub use ptr_extern::{PtrExtern, PtrExternCtor};
6
7use crate::traits::{Boxed, OpenCVTypeExternContainerMove};
8
9mod ptr_extern;
10mod ptr_f32;
11
12/// This is similar to Rust `Arc`, but handled by the C++. Some OpenCV functions insist on accepting `Ptr` instead of a heap
13/// allocated object, so we need to satisfy those.
14///
15/// [docs.opencv.org 3.x](https://docs.opencv.org/3.4/d0/de7/structcv_1_1Ptr.html)
16/// [docs.opencv.org 4.x](https://en.cppreference.com/w/cpp/memory/shared_ptr)
17pub struct Ptr<T: ?Sized>
18where
19	Self: PtrExtern,
20{
21	ptr: *mut c_void,
22	_d: PhantomData<T>,
23}
24
25impl<T: ?Sized> Ptr<T>
26where
27	Self: PtrExtern,
28{
29	/// Create a new `Ptr` from the object
30	pub fn new(val: T) -> Self
31	where
32		T: OpenCVTypeExternContainerMove + Sized,
33		Self: PtrExternCtor<T>,
34	{
35		unsafe { Self::from_raw(Self::extern_new(val.opencv_into_extern())) }
36	}
37
38	/// Create a new `Ptr` which points to `NULL`
39	///
40	/// Not generally useful, mostly for internal use.
41	///
42	/// # Safety
43	/// Should only be used as an argument to OpenCV functions that accept `Ptr` to `NULL`.
44	pub unsafe fn new_null() -> Self {
45		unsafe { Self::from_raw(Self::extern_new_null()) }
46	}
47
48	/// Get raw pointer to the inner object
49	pub fn inner_as_raw(&self) -> *const c_void {
50		unsafe { self.extern_inner_as_ptr() }
51	}
52
53	/// Get mutable raw pointer to the inner object
54	pub fn inner_as_raw_mut(&mut self) -> *mut c_void {
55		unsafe { self.extern_inner_as_ptr_mut() }
56	}
57}
58
59impl<T: ?Sized> Boxed for Ptr<T>
60where
61	Self: PtrExtern,
62{
63	#[inline]
64	unsafe fn from_raw(ptr: *mut c_void) -> Self {
65		Self { ptr, _d: PhantomData }
66	}
67
68	#[inline]
69	fn into_raw(self) -> *mut c_void {
70		ManuallyDrop::new(self).ptr
71	}
72
73	#[inline]
74	fn as_raw(&self) -> *const c_void {
75		self.ptr
76	}
77
78	#[inline]
79	fn as_raw_mut(&mut self) -> *mut c_void {
80		self.ptr
81	}
82}
83
84impl<T: ?Sized> Drop for Ptr<T>
85where
86	Self: PtrExtern,
87{
88	fn drop(&mut self) {
89		unsafe { self.extern_delete() }
90	}
91}
92
93unsafe impl<T: Send> Send for Ptr<T> where Self: PtrExtern {}
94
95unsafe impl<T: Sync> Sync for Ptr<T> where Self: PtrExtern {}