11use super :: PyType ;
2- use crate :: { Context , Py , PyPayload , PyResult , class:: PyClassImpl , types:: Representable } ;
2+ use crate :: {
3+ AsObject , Context , Py , PyObject , PyPayload , PyResult , VirtualMachine ,
4+ class:: PyClassImpl ,
5+ types:: { Destructor , Representable } ,
6+ } ;
7+ use core:: ffi:: c_void;
8+ use core:: sync:: atomic:: AtomicPtr ;
39
410/// PyCapsule - a container for C pointers.
511/// In RustPython, this is a minimal implementation for compatibility.
612#[ pyclass( module = false , name = "PyCapsule" ) ]
7- #[ derive( Debug , Clone , Copy ) ]
13+ #[ derive( Debug ) ]
814pub struct PyCapsule {
9- // Capsules store opaque pointers; we don't expose the actual pointer functionality
10- // since RustPython doesn't have the same C extension model as CPython.
11- _private : ( ) ,
15+ ptr : AtomicPtr < c_void > ,
16+ destructor : Option < unsafe extern "C" fn ( _: * mut PyObject ) > ,
1217}
1318
1419impl PyPayload for PyCapsule {
@@ -18,8 +23,26 @@ impl PyPayload for PyCapsule {
1823 }
1924}
2025
21- #[ pyclass( with( Representable ) , flags( DISALLOW_INSTANTIATION ) ) ]
22- impl PyCapsule { }
26+ #[ pyclass( with( Representable , Destructor ) , flags( DISALLOW_INSTANTIATION ) ) ]
27+ impl PyCapsule {
28+ pub fn new (
29+ ptr : * mut c_void ,
30+ destructor : Option < unsafe extern "C" fn ( _: * mut PyObject ) > ,
31+ ) -> Self {
32+ Self {
33+ ptr : ptr. into ( ) ,
34+ destructor,
35+ }
36+ }
37+
38+ pub fn pointer ( & self ) -> * mut c_void {
39+ self . ptr . load ( core:: sync:: atomic:: Ordering :: Relaxed )
40+ }
41+
42+ fn destructor ( & self ) -> Option < unsafe extern "C" fn ( _: * mut PyObject ) > {
43+ self . destructor
44+ }
45+ }
2346
2447impl Representable for PyCapsule {
2548 #[ inline]
@@ -28,6 +51,15 @@ impl Representable for PyCapsule {
2851 }
2952}
3053
54+ impl Destructor for PyCapsule {
55+ fn del ( zelf : & Py < Self > , _vm : & VirtualMachine ) -> PyResult < ( ) > {
56+ if let Some ( destructor) = zelf. destructor ( ) {
57+ unsafe { destructor ( zelf. as_object ( ) . as_raw ( ) . cast_mut ( ) ) } ;
58+ }
59+ Ok ( ( ) )
60+ }
61+ }
62+
3163pub fn init ( context : & ' static Context ) {
3264 PyCapsule :: extend_class ( context, context. types . capsule_type ) ;
3365}
0 commit comments