7 unstable releases

0.3.0 Sep 9, 2019
0.2.1 Jan 7, 2019
0.2.0 May 21, 2017
0.1.2 Dec 2, 2016
0.0.0 Sep 9, 2016

#2102 in Rust patterns

Download history 103/week @ 2024-03-13 88/week @ 2024-03-20 85/week @ 2024-03-27 102/week @ 2024-04-03 112/week @ 2024-04-10 83/week @ 2024-04-17 107/week @ 2024-04-24 133/week @ 2024-05-01 111/week @ 2024-05-08 128/week @ 2024-05-15 102/week @ 2024-05-22 81/week @ 2024-05-29 82/week @ 2024-06-05 101/week @ 2024-06-12 75/week @ 2024-06-19 78/week @ 2024-06-26

348 downloads per month
Used in libphonenumber-sys

MIT/Apache

84KB
1.5K SLoC

Utilities for interoperability with C++

See the project's README for more information.

The API is not stable yet. Breaking changes may occur in new minor versions.

Pointers

cpp_utils provides three kinds of pointers:

  • CppBox: owned, non-null (corresponds to C++ objects passed by value)
  • Ptr and MutPtr: possibly owned, possibly null (correspond to C++ pointers)
  • Ref and MutRef: not owned, non-null (correspond to C++ references)

Accessing objects through these pointers is inherently unsafe, as the compiler cannot make any guarantee about the validity of pointers to objects managed by C++ libraries.

Unlike Rust references, these pointers can be freely copied, producing multiple mutable pointers to the same object, which is usually necessary to do when working with C++ libraries.

Pointer types implement operator traits and delegate them to the corresponding C++ operators. This means that you can use ptr1 + ptr2 to access the object's operator+.

Pointer types implement Deref and DerefMut, allowing to call the object's methods directly. In addition, methods of the object's first base class are also directly available thanks to nested Deref implementations.

If the object provides an iterator interface through begin() and end() functions, pointer types will implement IntoIterator, so you can iterate on them directly.

Casts

The following traits provide access to casting between C++ class types:

  • StaticUpcast safely converts from a derived class to a base class (backed by C++'s static_cast).
  • DynamicCast performs a checked conversion from a base class to a derived class (backed by C++'s dynamic_cast).
  • StaticDowncast converts from a base class to a derived class without a runtime check (also backed by C++'s static_cast).

Instead of using these traits directly, it's more convenient to use static_upcast, static_downcast, dynamic_cast helpers on pointer types.

The CastFrom and CastInto traits represent some of the implicit coercions available in C++. For example, if a method accepts impl CastInto<Ptr<SomeClass>>, you can pass a Ptr<SomeClass>, MutPtr<SomeClass>, &CppBox<SomeClass>, or even Ptr<DerivedClass> (where DerivedClass inherits SomeClass). You can also pass a null pointer object (NullPtr) if you don't have a value (Ptr::null() is also an option but it can cause type inference issues).

No runtime deps