-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Allow creating PyCapsule objects
#7595
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+51
−11
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,14 +1,19 @@ | ||||||
| use super::PyType; | ||||||
| use crate::{Context, Py, PyPayload, PyResult, class::PyClassImpl, types::Representable}; | ||||||
| use crate::{ | ||||||
| AsObject, Context, Py, PyObject, PyPayload, PyResult, VirtualMachine, | ||||||
| class::PyClassImpl, | ||||||
| types::{Destructor, Representable}, | ||||||
| }; | ||||||
| use core::ffi::c_void; | ||||||
| use core::sync::atomic::AtomicPtr; | ||||||
|
|
||||||
| /// PyCapsule - a container for C pointers. | ||||||
| /// In RustPython, this is a minimal implementation for compatibility. | ||||||
| #[pyclass(module = false, name = "PyCapsule")] | ||||||
| #[derive(Debug, Clone, Copy)] | ||||||
| #[derive(Debug)] | ||||||
| pub struct PyCapsule { | ||||||
| // Capsules store opaque pointers; we don't expose the actual pointer functionality | ||||||
| // since RustPython doesn't have the same C extension model as CPython. | ||||||
| _private: (), | ||||||
| ptr: AtomicPtr<c_void>, | ||||||
| destructor: Option<unsafe extern "C" fn(_: *mut PyObject)>, | ||||||
| } | ||||||
|
|
||||||
| impl PyPayload for PyCapsule { | ||||||
|
|
@@ -18,8 +23,26 @@ impl PyPayload for PyCapsule { | |||||
| } | ||||||
| } | ||||||
|
|
||||||
| #[pyclass(with(Representable), flags(DISALLOW_INSTANTIATION))] | ||||||
| impl PyCapsule {} | ||||||
| #[pyclass(with(Representable, Destructor), flags(DISALLOW_INSTANTIATION))] | ||||||
| impl PyCapsule { | ||||||
| pub fn new( | ||||||
| ptr: *mut c_void, | ||||||
| destructor: Option<unsafe extern "C" fn(_: *mut PyObject)>, | ||||||
| ) -> Self { | ||||||
| Self { | ||||||
| ptr: ptr.into(), | ||||||
| destructor, | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| pub fn pointer(&self) -> *mut c_void { | ||||||
| self.ptr.load(core::sync::atomic::Ordering::Relaxed) | ||||||
| } | ||||||
|
|
||||||
| fn destructor(&self) -> Option<unsafe extern "C" fn(_: *mut PyObject)> { | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. does
Suggested change
compile? |
||||||
| self.destructor | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| impl Representable for PyCapsule { | ||||||
| #[inline] | ||||||
|
|
@@ -28,6 +51,15 @@ impl Representable for PyCapsule { | |||||
| } | ||||||
| } | ||||||
|
|
||||||
| impl Destructor for PyCapsule { | ||||||
| fn del(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<()> { | ||||||
| if let Some(destructor) = zelf.destructor() { | ||||||
| unsafe { destructor(zelf.as_object().as_raw().cast_mut()) }; | ||||||
| } | ||||||
| Ok(()) | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| pub fn init(context: &'static Context) { | ||||||
| PyCapsule::extend_class(context, context.types.capsule_type); | ||||||
| } | ||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: RustPython/RustPython
Length of output: 100
🏁 Script executed:
Repository: RustPython/RustPython
Length of output: 1782
🏁 Script executed:
Repository: RustPython/RustPython
Length of output: 101
🏁 Script executed:
Repository: RustPython/RustPython
Length of output: 47
🌐 Web query:
Python C API PyCapsule_New null pointer requirement💡 Result:
Yes, the Python C API function PyCapsule_New explicitly requires that the pointer argument must not be NULL. Passing a NULL pointer will raise a ValueError: "PyCapsule_New called with null pointer". From the official documentation: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) "Create a PyCapsule encapsulating the pointer. The pointer argument may not be NULL. On failure, set an exception and return NULL." This requirement is consistent across Python versions, including the latest (3.14.3) and earlier stable versions like 3.11. A valid capsule must have a non-NULL pointer, as stated in PyCapsule_IsValid: "A valid capsule is non-NULL, passes PyCapsule_CheckExact, has a non-NULL pointer stored in it, and its internal name matches the name parameter." Errors like "PyCapsule_New called with null pointer" occur when libraries (e.g., matplotlib on Windows) inadvertently pass NULL, which is a bug in the caller, not the API itself. Users should ensure the pointer is valid before calling PyCapsule_New and check the return value for NULL (due to memory allocation failure).
Citations:
Validate that the capsule pointer is non-NULL before constructing the object.
The Python C API explicitly forbids
NULLpointers inPyCapsule_New()and raises aValueErrorif one is passed. Additionally,PyCapsule_IsValid()requires a non-NULL pointer as part of its validity check. This constructor currently accepts null pointers without validation, allowing callers to construct capsules that violate CPython semantics. The non-fallible signature prevents proper error handling; consider returningResult<Self, ...>or validating the pointer before storing it.🤖 Prompt for AI Agents