CPPGIR(1)
cppgir β GObject-Introspection C++ binding wrapper generator π
okay bestie, welcome to the CPPGIR(1) page from the General Commands Manual β¨ this is the whole thing, every flag, every vibe, no skips π«Ά
β¨ NAME β¨
cppgir β GObject-Introspection C++ binding wrapper generator π
πΈ SYNOPSIS πΈ
cppgir [OPTION...] --output DIRECTORY GIR...
π DESCRIPTION π
So here's the whole situation, bestie: cppgir reads every GIR you hand it and converts them β plus any dependencies they drag along β into C++14 wrapper code. Collectively, all that code makes up a 'binding' (that's the GObject-Introspection terminology, check it out at https://wiki.gnome.org/Projects/GObjectIntrospection, it's giving official β¨).
Each GIR can be specified either as a full pathname to the .gir file, or just by the basename β no path, no .gir suffix β with or without a version. But lowkey, in that second case the .gir has to live in a standard location, or you've gotta pass other options to spell out where else it might be. fr fr. π¦
β¨ OPTIONS β¨
π Peep BACKGROUND later on for more deets on some of the concepts used in the descriptions below. iykyk.
--output DIRECTORYβ tells it the top-level directory to generate code into. It'll be created if it doesn't already exist. π--gir-path PATHSβ adds a colon-separated list of extra directories to (recursively) search for a.girfile in, for when you didn't specify it by full pathname.--debug LEVELβ debug level, aka how loud it is. Higher numbers = more verbose. π£οΈ--ignore FILESβ adds a colon-separated list of so-called ignore files.--suppression FILESβ adds a colon-separated list of so-called suppression files.--gen-suppression FILEβ names a suppression file to generate during this run.--classβ requests generation of the implementation class code you need for subclassing.--class-fullβ requests generation of a plain, as-is C signature fall-back method for an otherwise unsupported unwrapped method. Only applicable if--classis also specified. It also requires use of the latest custom subclass (signature) approach (details on that below), because these plain methods are not "activated" in the case of the legacy approach (for backwards compatibility).--expectedβ uses an error return type based on the std::expected proposal (http://wg21.link/p0323), instead of throwing an exception.--dlβ usesdlopen/dlsymto generate (most) calls rather than the usual "direct" calls. Because of that, a great many calls might then fail at runtime. So if you combine it with--expected, all those calls will use that error return type from above. π--const-methodβ marks (almost) all generated methods in the generated wrappers asconst. Alternatively β and perhaps more recommended β see also the helpergi:cs_ptrtype. π--class-args MIN_OPTIONALβ if>= 0, this is the minimum number of non-required arguments that triggers generation of aCallArgssignature variant (details below).--basic-containerβ also generates a collection signature for an input collection of basic type (likeint, etc). See below for some details and discussion.--output-topβ also generates convenience.cppand.hppfiles in the root output directory, per namespace, as may be useful for some build tool setups. π οΈ--dump-ignoreβ (only if compiled with embedded ignore) dumps embedded ignore data.
π ENVIRONMENT π
Instead of command-line options, environment variables can also be used. But note, bestie: options are still taken into account even when the variables have been set. π
These environment variables are considered, and they mean exactly the same thing as their corresponding command-line option:
`GI_DEBUG`, `GI_IGNORE`, `GI_SUPPRESSION`, `GI_GEN_SUPPRESSION`, `GI_OUTPUT`,
`GI_CLASS`, `GI_CLASS_FULL`, `GI_EXPECTED`, `GI_DL`, `GI_GIR_PATH`
On top of all that, GI_GIR can specify a colon-separated lists of GIRs (specified the same way as on the command line). XDG_DATA_DIRS is also used as an additional source of directories to search for GIRs (within a gir-1.0 subdirectory). π
π¦ BACKGROUND π¦
β¨ API v2 β¨
Heads up: the v2 API is somewhat different from the previous API, so some porting of your existing code may be needed. There's also a later section with the rationale and a discussion of the changes. π«Ά
The generated code gives you a straight binding as specified by the annotations, so everything is pretty much where you'd expect it β methods inside classes, classes inside namespaces, the whole iconic layout. For example, all GObject types live inside namespace gi::repository::GObject. With that in mind, using and navigating the generated code should be easy, along with these following comments:
- As is customary, anything inside a
detailorinternalnamespace is not meant for public use and is subject to change. The top-levelginamespace defines a few things that make up the public API, which is meant to be stable (though at this stage of maturity, no full guarantee is provided). - Some generated code may have
_(an underscore) appended to it, purely to avoid clashing with a reserved keyword (or a preprocessor definition). Otherwise it has no special (reserved) meaning. - However, anything with a leading underscore (if you encounter it) should be considered internal (and not meant for the public API). π
In overall, the generated code is very lightweight and clear, easily understood, and with little runtime overhead β as also illustrated by the following overview of wrappers for various kinds of types. Note that almost all of them essentially wrap a pointer, and therefore should be checked for validity prior to many uses, just like with any "smart pointer" (e.g. using the provided operator bool()). β¨
π Objects
A GObject is a single pointer, along with class code that manages a single refcount (including decrementing it upon destruction). The refcount it manages is either received/taken from a full transfer, or ref_sink'ed (in the case of none/floating transfer β see also the discussion in the subsequent section on the intricacies of the latter and some theoretical edge cases).
π Boxed Types
Similar, but with a minor twist: wrappers for a boxed GType MyBox come in 2 kinds β an owning MyBox and a non-owning MyBox_Ref. In both cases, the wrapper is again a single pointer with some suitable/applicable helper methods. The former essentially acts as a "unique ptr" (with g_boxed_free as the deleter), whereas the latter acts as a "naked ptr/reference" (with no ownership or cleanup at all). Obviously, for that latter case, all the usual caution regarding dangling references (etc) applies. The non-owning ones get used for transfer none cases, and the owning ones in transfer full situations.
If you need a safe "reference" to keep around (say, in some member), then a _Ref can be .copy_()'d (which uses g_boxed_copy) into an owning wrapper. The above semantics also imply that the owning wrapper is move-only (and again, .copy_() yields a copy).
However! There are quite some cases where a boxed copy is based on a refcount (which also preserves the box identity/pointer). Those cases have been specially marked (in overrides) to make the owning wrappers copyable as well. Likewise, a _Ref of such cases can be (implicitly) assigned/copied to an owning one (in each case triggering a g_boxed_copy, which is then known to be plain and cheap).
If you want, additional wrappers could be marked as copyable, in which case a wrapper copy invokes a potentially more expensive (and non-identity-preserving) g_boxed_copy. Also, or alternatively, if GI_ENABLE_BOXED_COPY_ALL is defined and truthy, then all boxed wrappers are copyable in that way. π
πΈ Record Types
Plain records (i.e. structs with no registered GType) are handled in a similar fashion, with g_free as the "deleter" (and without any copy support). Since there's no lifecycle resource management (construction, destruction) available for such types, there are (quite some) limitations to what code generation or binding can do here β see also the discussion in the corresponding section. π
π§ Strings
A string (e.g. char*) is also regarded and wrapped in a similar way. That is, a gi::cstring wraps (and owns and manages) a C char*, and gi::cstring_v is the corresponding non-owning variant. Obviously, the former bears a resemblance to std::string, whereas the latter resembles std::string_view.
In fact, since there's no real definitive "string API" (in C or glib), their API is fairly similar (though not guaranteed identical) to the std counterparts. Also, various conversions from/to the std counterparts should allow for convenient type interchange. Additional integration with other string types is also possible, by further specialization of gi::convert::converter (see the gi/string.hpp source for details). π
π Collections
That is, GList, GSList, GPtrArray, GHashTable, or plain arrays (zero-terminated or not). Similar to a std container, each collection wrapper is a templatized gi::Collection type, with (a.o.) a type parameter for the contained type.
As with some of the types above, such wrappers come in owning and non-owning variants, as specified by another (type) parameter and obtained from annotations, i.e. transfer none, transfer container, or transfer full. Note that the "ownership" specifies ownership of both the container and the contained elements. Of course, where needed, code generation will select and specify the proper type (e.g. as a function parameter).
Following aspects are worth mentioning:
- Templatized constructors and conversion operators support construction from/of and assignment from/to (e.g.)
stdcontainer types. Likewise for "similar" (duck-ed) types, where "similar" refers to member types and constructor signatures. π¦ - A (
std) container-ish API is also provided, though it's neither identical nor fully compatible (a.o. due to limitations of the C wrappee's API). However, the none (ownership) variant is considered read-only, so it doesn't provide any of the "modification" API parts and only aconstiterator. As almost no wrapper methods areconst, anauto p : coll(range-for) pattern is recommended (wrappers are cheaply copied). The other variants do support modification as well as iteration that allows for anauto &p : collpattern (if so desired). In particular, this applies to the full variant, which is the recommended one for "standalone" use (as a container), since it safely manages ownership of both itself and its elements. - Wrappers of refcounted collections (
GPtrArray,GHashTable) are otherwise similar to object wrappers. So they always manage a refcount (and are copyable) regardless of ownership variant (none, etc). The other wrappers are similar to boxed wrappers, e.g. copyable in the none variant, but otherwise assume unique ownership and are non-copyable. π - A
gi::CollectionParametermay also get used by code generation for a function input parameter. If there's no ownership involved, this type/instance will temporarily hold ownership of a collection that might have been conjured up by converting from some other container. "Temporarily" here means: for however long the call lasts, i.e. the lifespan of that parameter instance. It is not β and fr should not be β used anywhere else. π ββοΈ - For an input collection parameter of a basic type (say
int), the original C signature is typically the vibe. That's 2 parameters (int*andgsize). Why tho? Because that exact same signature may also show up for an output collection (of specified input size). Keeping the original signature means it works whether or not the annotation is correct β and it might not be, since these APIs are usually "low-level" (buffers and such), so "scripted binding" often doesn't even look at them. It's also just an efficient, clear API, because any buffer's "location" (likestd::vectoror whatever) can easily be handed over via those 2 parameters. That said, if you want it and you say so with the--basic-containeroption, an extra collection-based signature gets generated too. β¨
In short: you can choose to roll with std types and convert to collection wrappers at function call/return time β but for simple cases (or beyond), the collection wrapper itself might well do the job, no conversion needed. π
Plain Types. All the various enums, (static) methods, functions, typedefs (for callbacks) β they fill in the rest. π«Ά
Functions. Functions that use the usual GError return pattern get wrapped a couple different ways. On one hand, in a straight way, where the error is a (wrapped error) output parameter. Alternatively, the error parameter gets removed from the signature. When that happens, it gets "returned" either by throwing the (wrapped) error β which is also a std::exception subclass β or by returning a suitable expected type (with the wrapped error type as its error type). Throwing is the default behaviour, and you can request the other one with the --expected option.
If there's a GError in a (function) callback or virtual method signature, it's always retained as a (wrapped) error output parameter, and it's preferably used to report an error that way. Alternatively, an exception can be thrown β preferably a GLib::Error instance then. Callback wrapping code will catch any exception and report it (back to the C caller) using the GError output, along with a zero-initialized return value, which is likely β but not necessarily β a good choice. π
Heads up bestie: that catch only kicks in if exception support is enabled. Auto-detection of this should usually work, but if you need to, you can specify it by defining GI_CONFIG_EXCEPTIONS explicitly (truth/falsy).
If a function has (non-GError) output parameters, then there's a signature where those outputs are parameters (just like the plain C case), plus another variant where they get folded into the return value, which may then become a std::tuple<> type.
If so configured, some so-called CallArgs variations may also be generated. In that case, (roughly) a custom xyz_CallArgs struct type gets generated (for each function xyz), with members corresponding to the function arguments, along with a function that takes 1 argument (of that custom struct type). When there are lots of (optional) arguments, that argument could be specified using designated initializer syntax, which allows a sort-of "call by keyword". Again, there are variations with output parameters as return value or not. Besides some potential advantages, there are also some drawbacks though. First and foremost: when you use the member names in designated initializers, those names become essentially part of the API β even though the name's origin as a plain C function parameter provides no stability guarantee. π Also, suffice it to say a great many struct types can be generated this way. You could mitigate that by employing a suitable "generation level", e.g. 2. In that case, only functions that have at least 2 (or more) non-required arguments will have such a custom type and signature generated.
Subclasses and Interfaces. Some extra specifications on how subclasses and interfaces get mapped may also be in order. A subclass in the GObject world maps directly as a subclass in the C++ binding. However, if a GObject implements an interface, the generated class does not inherit from the interface's (generated) class. This is mostly a matter of implementation choice (and to keep its lightweight simplicity). Also, knowledge of implemented interfaces isn't always available at compile time β e.g. in the case of dynamically loaded GStreamer elements (though it's more likely in the case of the Gtk hierarchy). Since there'd be no inheritance in the dynamic case anyway, the consistent choice is to not have it at any time. But for ease of use, some helper code is generated when an implemented interface is known at generation/compile time, as illustrated in the following snippet from an example:
// use a cast if not known, either to a class or interface
auto bin = gi::object_cast<Gst::Bin>(playbin_);
// known at compile time; overloaded interface_ method
auto cp = bin.interface_ (gi::interface_tag<Gst::ChildProxy>());
π SUBCLASS IMPLEMENTATION API π
There may be times when you'd wanna make a custom subclass of GObject, or of some Gtk widget. In the same vein, the (current) implementation choices imply that you should not simply inherit from Gtk::Window. Part of the motivation here is that this kind of subclassing depends on style and setting β i.e. it's pretty rare when you're in a GStreamer setting, but less so in e.g. Gtk. So the possibly-rare cases shouldn't burden or complicate the basic wrapping use case. π
Before we get into the details of "how", let's first consider what a "subclass" actually means in this context. It'll probably involve a (C++) (sub)class of some generated class (related to a GObject class type), with potentially extra/custom properties and signals. In particular, that last bit implies it also involves a new GType that defines a subtype (of the aforementioned GObject class type). An instance of such a class/type then consists of a C++ instance that's 1-to-1 associated with a GObject instance of the custom defined (sub) GType.
In turn, this leads to (at least, for now) 2 possible ways to create instances:
- triggered on the C++ side, in the usual way through a constructor. The bottom of the constructor chain registers a custom
GType(if still needed), creates an instance (g_object_new()) and associates it (with the C++ instance).
The advantage: standard use of a C++ constructor applies. The downside: the defined GType can not be (safely) used in the GObject (eco)system, because any g_object_new()'d instance is incomplete (it lacks a C++ instance). π
- triggered on the C side by
g_object_new(). In this case, the registered type's custom (GObject) constructor first delegates to the parent constructor to create a GObject subtype instance, and thennews a C++ object β and again the bottom of the constructor chain associates it with the created GObject instance.
In this case, an instance has to be created based on GType. However, this type can be safely used in any GType based factory system, e.g. when referenced (by name) in an XML/UI file or (by number) in a GStreamer plugin factory. π₯
So, to summarise: (up to) 2 different ways to create objects, and so (up to) 2 different custom GTypes that a "subclass" can define. The latter one is more recent and is also the recommended approach, since instances are always properly created. Also, if you want, some additional helper new_() member can be defined that acts as a surrogate constructor. π
So how do you subclass then? By a slight twist β using the impl namespace variations, as in this excerpt from an example:
class TreeViewFilterWindow : public Gtk::impl::WindowImpl
{
// ...
public:
// Assume (hypothetically) that Window also implements FakeInterface
// with a set_focus method, then a compilation failure will be triggered (as
// it can no longer be detected whether set_focus is defined in this class).
// Then the following inner struct is needed to resolve so manually;
struct DefinitionData
{
// the last parameter specifies whether the method is defined
// (which may well be false in all class/interface cases if not defined)
GI_DEFINES_MEMBER(WindowClassDef, set_focus, true)
GI_DEFINES_MEMBER(FakeInterfaceDef, set_focus, false)
};
// NOTE for the auto-detection to work, the methods must be accessible
// so either they should be defined public, or (e.g.) WindowClassDef
// must be declared friend, or the above manual resolution can be used.
// this (super)constructor signature leads to a C++ side type
TreeViewFilterWindow () : Gtk::impl::WindowImpl (this)
{
// ...
}
// this (super)constructor signature leads to a C-side type
// NOTE InitData is not (easily) instantiated,
// so this constructor is only used by the internal C-side mechanics
TreeViewFilterWindow (const InitData &id)
: Gtk::impl::WindowImpl (this, id, "TreeViewFilterWindow")
void set_focus_ (Gtk::Widget focus) noexcept override
{
}
// the above constructor is also re-used during (C-side) type registration
// (in that case with an "empty" id and no associated GObject setup)
// that can avoided by providing a separate ...
GType get_type_()
{
// no interfaces, properties or signals to declare
return register_type_<TreeViewFilterWindow>("TreeViewFilterWindow", 0, {}, {}, {});
}
};
// create an instance of (either) type
// it prefers the latter C-side type, if supported, and supports extra arguments
// (a second template parameter allows for specific selection,
// see code comments and examples for details)
gi::make_ref<TreeViewFilterWindow>()
Parent (class or interface) methods can then be overridden or implemented in the usual way β just define them in the subclass. It's also possible to define custom signals and properties in the subclass, as illustrated in the gobject.cpp example. As mentioned, that inner DefinitionData struct in the above fragment is usually not needed β only in the case of conflict/duplication of class/interface member(s). πΈ
So likeβ¦ this whole virtual-methods thing is an optional feature, bestie π
, which means the impl parts are not generated by default β they only show up if you pass --class. And since virtual methods share some similarities with callbacks, they're also subject to some limitations (go peep the corresponding section for that whole situation π). Which means it can happen that some virtual methods don't have a wrapper at all π. If you pass --class-full, then a passthrough virtual method (with the C signature exactly as-is) gets generated instead, and you can override and implement that as a fallback π«Ά. So the custom type registration (which happens behind the scenes, sneaky little thing) can still be used β just at the expense of dealing with a plain C signature and types (which is basically the same vibe as directly calling a C function as a fallback if no wrapper function was generated for some reason).
Also, this is a fairly advanced feature, no cap, with various aspects that are not immediately obvious π. For example, the resulting "instances" have "2 sides" β there's a C++ object instance and an associated (derived) GObject instance (which internally refer to each other in a 1-to-1 association). Which means their destruction has to be closely coordinated. And that's potentially tricky bc the GObject side is traditionally reference-counted, whereas the C++ object could be literally anything (stack-allocated or otherwise). The latter can be stack-allocated if you make sure there's no lingering reference in the GObject world. So it depends on the use-case how to proceed. But overall, it's probably recommended to manage lifetime and ownership based on the GObject (side) reference count. The gi::make_ptr and gi::ref_ptr helpers are lowkey helpful in this regard β¨.
There are also situations where the C API (implementation) involves some "low-level tricks" that don't port over in a simple or straight way (e.g. GtkBuilder π). Those are likely in need of some custom overrides or extensions (see also below) which may or may not already be provided for some particular API/situation. It is highly advised to browse provided overrides and extensions and/or consult the closest relevant related example (which usually showcases what's available, along with additional explanations π).
π§± CODE LAYOUT AND BUILD SETUP π§±
The generated code gets written to the top-level with this layout, okay? Each GIR namespace has a corresponding subdirectory, say ns (and also a C++ namespace, cppgir::repository::ns πΈ). The top-level headers for a namespace are then:
ns.hppβ a regular header providing the namespace's declarations. It will also include the dependent namespaces' top headers. If the macroGI_INLINEis defined, then it will also include ...ns_impl.hppβ contains the definitions corresponding to the declarations. Normally this would be a.cppfile, but as they might be included directly in the inline case, they've been namedxxx_impl.hppinstead.ns.cppβ this merely includesns_impl.hppand is as such no different than the latter, except for more traditional naming. Compiling this file in the non-inline case provides all the definitions for the namespace in the resulting object file.*.cppm; module wrappers, see next subsection for details.
So, in summary, it comes down to setting up the build system to build each of the namespaces' .cpp, as is also done in this repo's CMake build setup π οΈ. There is one other shortcut build setup that is illustrated by the gtk-obj.cpp example file, which includes all definitions (recursively):
#define GI_INCLUDE_IMPL 1
#include <gtk/gtk.hpp>
Note, however, this is only possible if there is exactly 1 top-level namespace, as doing this for several namespaces will lead to duplicate definitions π΅.
Some items (functions, types) may be marked as deprecated (in source code), while still present in GIR data. Wrappers will still be generated and pragma are issued to avoid warnings that might otherwise occur. Generic gi support tries to avoid using deprecated code. There is, however, one exception regarding the use of g_object_newv, which is deprecated but may have to be used if support for an older GLib is required. This can be arranged by defining GI_OBJECT_NEWV (and the deprecation warning should also be silenced when dealing with newer version π). If the items are also marked deprecated in GIR data, then these are skipped by default. However, if the string deprecated:<NAMESPACE>:<VERSION> matches (a regexp) in specified ignore data/files, then deprecated items will be considered for the namespace in question, after being checked as usual against the ignore list.
If you've specified the --class option, then the generated code will possibly contain classes that inherit from several classes (representing interfaces). Since various interfaces may have overlapping member names, this might trigger compilation warnings π. These are not suppressed by default, as you may need to be made aware of this. However, if it does no harm in your particular case, then defining GI_CLASS_IMPL_PRAGMA should arrange for proper suppression β¨.
The generated code may be quite extensive and so it may present a "heavy build". Other than that, the above allows for a number of different build setups, and cppgir tries not to impose any particular approach. In particular, standard tried-and-tested build optimizations can be applied, such as precompiled headers (with some good results, as reported in issue #99 https://gitlab.com/mnauw/cppgir/-/issues/99 π₯).
π C++ Module support π
At this time of writing, module support is still new-ish in compilers and (not in the least) build tools π. Unfortunately, all major compilers also take a different approach in handling these wrt command-line argument, source file extension or binary output. Note that this also likely complicates any compile_commands.json based tooling (e.g. LSP server as used by IDEs) along with other issues as outlined in this post https://nibblestew.blogspot.com/2023/12/even-more-breakage-in-c-module-world.html and originally raised long ago https://vector-of-bool.github.io/2019/01/27/modules-doa.html π.
By comparison, precompiled headers are long since well supported, so these may be a more recommended alternative approach π.
Failing that, a next natural fit might be "header units" (in module spec sense). Unfortunately, compiler setup here varies somewhat and build tool support may be limited π.
So, a next step is a pure/real module. Unfortunately, "core gi" can not be provided in that form;
- in addition to code, it also "exports" some macros, which can not really be export'ed or import'ed (only from a "header unit")
- the core is somewhat intertwined with basic types from GObject, e.g. some code-generated types are forward declared (which satisfies for their purposes in "core gi"). However, forward and real declaration can not pass module boundary.
But "core gi" combined with (generated) GLib and GObject can be wrapped in a module (along with a separate "macro API header", gi_inc.hpp) π«Ά.
Again, cppgir does not impose a particular module layout/setup, but provides the basic parts and pieces to do so. The generated code also provides a few example module wrappers (with no stability guarantee), also see gst.cpp and gtk.cpp examples for possible usage details;
ns.cppm(exportsgi.repo.ns); module that wraps/providesns(inline) code, so a typical compilation produces.ocode ofnsand a BMI/CMI that exportsnsdeclarationsns_rec.cppm(exportsgi.repo.ns.rec); module that wraps/providesnsand all (recursive) dependencies, so a typical compilation produces.ocode ofnsand dependencies, along with a BMI/CMI with corresponding declarations.
The above have been tested with gcc-15 and clang-18 with some varied measure of success (apparently, GCC fails to link the non-recursive approach π¬). They each come with an extra "knob"; if GI_MODULE_EXTERN is defined, then the module purview is essentially extern "C++" { ... }. So all declarations are then attached to global module, as opposed to the named module, and as such do not incur any modified ABI linkage (@M) (so it may be recommended π
).
Other variations are likely possible, e.g. module partitions, separate module implementation, etc.
π OVERRIDING OR EXTENDING π
It is possible to add functions or methods or override existing names (by effect of name hiding π). To this end, the generated code contains various 'optional include hooks' using the __has_include directive. This way, code in externally supplied (include) files can be inserted into the class definition chain. There are roughly 3 such 'hook points':
- initial setup β this part is (conditionally) included before the namespace's C headers are included. This allows specifying define's to tweak subsequent headers or to add headers that also need to be include'd, and which may not have been specified in the GIR.
- class definition β these hooks allow extending the wrapped class with new or tweaked methods
- global extra definitions β these are included after all generated code, and supports adding of new global functions, typedef's, type trait helper declarations, ...
The reader is invited to examine the default overrides in this repo as well as the generated code to see how this fits together based on a simple naming scheme and use of macros π. In particular, see the provided GLib overrides. Suffice it to add that the _def suffix refers to 'default' as supplied by this repo and which are installed alongside the common headers. The corresponding non-suffixed filenames should be used by project specific custom additions β¨.
π¦ CODE GENERATION π¦
It might be necessary to exclude a GIR entry from processing, either because it is a basic type handled by custom code (e.g. GObject, GValue, ...) or because of a faulty annotation π. The latter can be a glitch in the annotation itself, or one that actually refers to a symbol in a non-included private header. The exclusion can be directed by so-called ignore files, and at least one such is supplied as a system default ignore containing known and essential cases to exclude (and without which code generation would not produce valid code π΅). Such a file consists of lines of regular expressions (# commented lines are ignored). At generation time, each symbol is turned into a <NAMESPACE>:<SYMBOLKIND>:<SYMBOL> string, and excluded if it matches one of the lines' regular expression. So, for instance, GObject:record:Value prevents processing of GValue, since there is already special-case code for that in the common header code. Further expression examples are found in the default ignore file. Additional files can be specified by the --ignore option π.
okay so bestie, as each entry gets processed, cppgir might slide a lil notification your way about an annotation that looks inconsistent, or a case it just can't deal with (peep BUGS AND LIMITATIONS for that tea π«). And once you've gone through all those reported cases by hand and decided they're harmless? You can mute the corresponding notices by feeding some suppression files to --suppression. The format of those files is literally the same as ignore files, except a match here just turns the reporting verbosity down a notch instead. You can hand-craft one, or β iconic behaviour β let a run auto-generate it for you by specifying --gen-suppression. π
And while we're vibing on excluding problematic GIR parts, lowkey you might also wanna consider solutions to some problematic GIRs other projects are using, like the fixed GIRs maintained by gtk-rs over at https://gtk-rs.org/gir/book/tutorial/finding_gir_files.html#gtk-dependencies, living in the referenced repo https://github.com/gtk-rs/gir-files. π¦
π (RATIONALE OF) v2 CHANGES π
okay so picture this python session using gobject-introspection:
>>> import gi
>>> gi.require_version('Gst', '1.0')
>>> from gi.repository import Gst
>>> Gst.init(None)
>>> c = Gst.caps_from_string('video/x-raw')
>>> c.get_structure(0)
<Gst.Structure object at 0x7fe284096760 (GstStructure at 0x1bb4420)>
>>> c.get_structure(0)
<Gst.Structure object at 0x7fe2840b5d00 (GstStructure at 0x1bb43a0)>
What is even happening here?? A different GstStructure* gets created every single time, even though the same one is returned (by C code) in each case. The python binding here has no other choice than to use g_boxed_copy() on the transfer none return value. If it didn't, it would be carrying around an unguarded/unowned and hence potentially dangling pointer (in some PyObject wrapper), which is a definite no-go in a scripted setting that must always ensure valid objects. π«
The v1 API followed a similary "scripted" style approach where all objects/pointers should always be safe and valid, with (roughly) std::shared_ptr in place of PyObject. Of course, also then with similar (copy) effects as in the above excerpt and in e.g. issue #32 https://gitlab.com/mnauw/cppgir/-/issues/32. π
v2 now follows a different approach. After all, C++ is much closer to C, and it is customary to mind about (potentially dangling) references and such, and where and how (not) to use e.g. std::string_view. And so while types/objects are now no longer always "owning" (and as such always safe), the type conventions do clearly specify whether or not they do (own). As such, standard C++ practices should handle what v2 API provides, while avoiding superfluous and potentially surprising copies or any other "automagic". In particular, the v2 bindings are therefore even more "tight and direct" than before, with a typical wrapper being only a cast away from the wrappee (and matching in size and semantics). β¨
Migration. In practice, only limited changes have been needed in the included examples. Of course, your mileage may vary, depending on usage of "boxed types" as well as use of (type deduction) auto versus explicit type specification. Some _Ref types may have to be used instead here or there, as well as possibly some std::move on "owning" variants (unless overall boxed copy is enabled). For reasons of consistency and to avoid collision with generated methods, some more "custom methods" may have had _ appended (e.g. CBoxed::allocate_()). π«Ά
π BUGS AND LIMITATIONS π
The generated code's coverage is pretty good and comfortably serves most cases that arise in practice as also illustrated by the examples. Nevertheless, the following should be mentioned:
Callback types. Only callback types that have an explicit user_data parameter are supported. That includes (fortunately) cases such as connecting to a signal, or a GstPadProbeCallback, though a GstPadChainFunction is excluded. The reason is a technical one; the user_data parameter is used to pass data used by callback wrapper code. A typical (script) runtime binding handles this using libffi's closure API (https://github.com/libffi/libffi). In effect, a little bit of executable code is then generated at runtime, and the address of that code then essentially serves as surrogate user_data that can carry extra meta-data for use by the runtime. This could also be employed here to lift the user_data limitation, it would take a bit extra work, but would more importantly then also incur an additional dependency. π§
Callback handling. Even if user_data is present, other aspects of a callback signature may not be supported (at this time), e.g. certain (sized) array parameters. However, few (if any) of such actual cases are known at this time. Note that both signals and virtual methods are somewhat similar to a callback and as such share similar limitations.
Whereas the above items could (in theory) be resolved, the following are more inherent limitations (by the very context and nature of e.g. annotations). Fortunately, though, the practical impact is fairly limited (if any).
const handling. In C++, this is a Bigger Thing. For instance, a simple 'getter' should preferably be marked const. However, on the original C-side of things, only very limited consideration is given to this. Even if there is some const, it is not treated with all that much respect, e.g. g_value_take_boxed starts const but it is merrily cast away along the way. As such, there is not much to find on const-ness in annotation data, and so no point in inventing any. Rather, the focus is simply on getting the proper function calls done along with automagic refcount and resource management (much as any runtime binding would do, with no regard for const whatsoever in that case).
In particular, methods are usually not marked const either, as there is similarly no (semantic) data to decide either way. As such, it is not recommended to use const wrapper types. However, they may arise due to generic templates or when captured in a lambda. In such cases, the helper (template) type gi::cs_ptr may be useful, or alternatively one might set the option to mark all code-generated methods as const.
Floating (into darkness). Gobject docs https://docs.gtk.org/gobject/floating-refs.html mention the following about floating references (i.e. transfer floating);
Floating references are a C convenience API and should not be used in modern GObject code. Language bindings in particular find the concept highly problematic, as floating references are not identifiable through annotations, ...
Indeed, by the time floating makes it into the parsed annotation, it has become none. And in case of a "factory" some_widget_new(), floating behaves more like full as the caller must "take ownership" to avoid a leak. So a "floating" none is quite different from a "real" none (e.g. "getter" method). But no way to know from annotation data. So, in case of none, an object wrapper always ref_sink()s. If it was floating, it has taken suitable ownership. If it was really none, then it is now managing an extra refcount. And in either case, it will release/decrement upon destruction. Essentially, this follows the recommendation given in referenced docs. In practice, it actually Just Works. π
It gets really tricky when this is combined with e.g. lists. So what does none mean in this case (in annotation)? In the worst case, the contained elements might actually be floating, so one would have to go through the list and ref_sink them all (un)conditionally? Suffice it to say, no such "automagic" is handled/injected by any wrapper code. Fortunately, at this time there does not seem to be such a "multiple factory" API. Even if there were, then in practice the calling code is likely to loop over the list and access the elements. The ensuing C++ wrappers (even if existing only briefly) would then effectively ref_sink(), so again we are ok. And last but not least, by the above quoted recommendation, there should be no such new tricky API coming along. So, again, it Just Works. If needed, any such old or new API can and should be handled by custom overrides.
Boxed (by darkness). This refers to so-called "plain records" which are "C structs" with no registered GType (referred to as "C boxed" types in cppgir code), e.g. GOptionEntry or GstMapInfo. While their fields may be described in annotations, there is no information regarding the "ownership" of any data (which may even vary upon context). In particular, also no way to create/free. This corresponds with their frequent stack-allocated use in C code in typically "low-level" API which is usually not considered "binding friendly". Based on the mild assumption that 0-initialized data makes a valid instance, they are treated somewhat similar to (GType) boxed types and as such can be used in some limited (function call) situations. Any improvement beyond that is likely to remain in the purview of overrides.
πΈ WORKAROUNDS πΈ
As C++ allows direct mixing/calls with C, there are usually some fallback workarounds when confronted with one of the limitations. First of all, note that a C++ wrapper typically has e.g. a gobj_() method that provides the underlying C pointer/object. Conversely, gi::wrap can be used to obtain a wrapper from a C pointer/object obtained by some means. With that in mind, the following are some workarounds;
- function call; using/given the above, the C function can then (simply) be called directly
- custom subclass virtual method; use
--class-fullto generate a virtual method with plain C signature - signal; use
Object::connect_unchecked(see alsogst.cppexample) - callback; use
gi::callback_wrapper(see also in same example location as above). Or perhaps there is an API variant using closures which may be useful in combination with someClosure::from_*helpers (see still same example).
π SEE ALSO π
and that's the whole page, bestie, you made it to the end and you ate π this was CPPGIR(1), dated November 2025 β go forth and bind responsibly, mwah π
ππ¦
π¦ where this page comes from
- ubuntu resolute: cppgir 2.0+git20250629.2a7d9ce-2 Β· MIT
- ubuntu stonking: cppgir 2.0+git20250629.2a7d9ce-2 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms