docs: expand documentation for operator substitutions

The replacements of * with [0], -> with ., and & with address_of_() are
documented in the Object class docstring, but they're important enough
that we should mention them in the user guide. Also expand the
documentation of __getitem__ and __getattribute__ to mention this.

Signed-off-by: Omar Sandoval <osandov@osandov.com>
This commit is contained in:
Omar Sandoval 2023-10-23 11:22:28 -07:00
parent a34be20882
commit 7cae874b71
2 changed files with 29 additions and 6 deletions

View File

@ -1203,6 +1203,9 @@ class Object:
"""
Implement ``self.name``.
This corresponds to both the member access (``.``) and member access
through pointer (``->``) operators in C.
If *name* is an attribute of the :class:`Object` class, then this
returns that attribute. Otherwise, it is equivalent to
:meth:`member_()`.
@ -1217,8 +1220,16 @@ class Object:
"""
Implement ``self[idx]``. Get the array element at the given index.
>>> print(prog['init_task'].comm[0])
(char)115
>>> print(prog['init_task'].comm[1])
(char)119
``[0]`` is also the equivalent of the pointer dereference (``*``)
operator in C:
>>> ptr_to_ptr
*(void **)0xffff9b86801e2968 = 0xffff9b86801e2460
>>> print(ptr_to_ptr[0])
(void *)0xffff9b86801e2460
This is only valid for pointers and arrays.
@ -1280,11 +1291,13 @@ class Object:
"""
Get a member of this object.
This is valid for structures, unions, and pointers to either.
This is valid for structures, unions, classes, and pointers to any of
those. If the object is a pointer, it is automatically dereferenced
first.
Normally the dot operator (``.``) can be used to accomplish the same
thing, but this method can be used if there is a name conflict with an
Object member or method.
Normally the dot operator (:meth:`. <__getattribute__>`) can be used to
accomplish the same thing, but this method can be used if there is a
name conflict with an ``Object`` member or method.
:param name: Name of the member.
:raises TypeError: if this object is not a structure, union, class, or

View File

@ -74,6 +74,16 @@ compared::
>>> prog['init_task'].nsproxy.mnt_ns.pending_mounts > 0
False
Python doesn't have all of the operators that C or C++ do, so some
substitutions are necessary:
* Instead of ``*ptr``, dereference a pointer with :meth:`ptr[0]
<drgn.Object.__getitem__>`.
* Instead of ``ptr->member``, access a member through a pointer with
:meth:`ptr.member <drgn.Object.__getattribute__>`.
* Instead of ``&var``, get the address of a variable with
:meth:`var.address_of_() <drgn.Object.address_of_>`.
A common use case is converting a ``drgn.Object`` to a Python value so it can
be used by a standard Python library. There are a few ways to do this: