| 1 | cppgir(1) - GObject-Introspection C++ binding wrapper generator |
| 2 | ================================================================== |
| 3 | |
| 4 | |
| 5 | ## SYNOPSIS |
| 6 | |
| 7 | `cppgir` [OPTION...] `--output` _DIRECTORY_ GIR... |
| 8 | |
| 9 | |
| 10 | ## DESCRIPTION |
| 11 | |
| 12 | `cppgir` reads each of the specified GIR and converts these (and any |
| 13 | dependencies) into C++14 wrapper code that collectively then make up a |
| 14 | 'binding' (in |
| 15 | [GObject-Introspection](https://wiki.gnome.org/Projects/GObjectIntrospection) |
| 16 | terminology). Each GIR can be specified as a full pathname to the `.gir` file |
| 17 | or simply by the basename (i.e. no path or `.gir` suffix), with or without |
| 18 | version. Of course, in the latter case, the `.gir` must be in a standard |
| 19 | location, or other options must specify additional whereabouts. |
| 20 | |
| 21 | ## OPTIONS |
| 22 | |
| 23 | See [BACKGROUND](#background) later on for further details on some of the |
| 24 | concepts used in the following descriptions. |
| 25 | |
| 26 | * `--output` _DIRECTORY_: |
| 27 | Specifies the top-level directory in which to generate code. |
| 28 | It will be created if it does not yet exist. |
| 29 | |
| 30 | * `--gir-path` _PATHS_: |
| 31 | Adds a colon-separated list of additional directories within which |
| 32 | to (recursively) search for a `.gir` file (if not specified by full pathname). |
| 33 | |
| 34 | * `--debug` _LEVEL_: |
| 35 | Debug level or level of verbosity, higher numbers are more verbose. |
| 36 | |
| 37 | * `--ignore` _FILES_: |
| 38 | Adds a colon-separated list of so-called ignore files. |
| 39 | |
| 40 | * `--suppression` _FILES_: |
| 41 | Adds a colon-separated list of so-called suppression files. |
| 42 | |
| 43 | * `--gen-suppression` _FILE_: |
| 44 | Specifies a suppression file to generate during this run. |
| 45 | |
| 46 | * `--class`: |
| 47 | Requests generation of implementation class code needed for subclassing. |
| 48 | |
| 49 | * `--class-full`: |
| 50 | Requests generation of a plain as-is C signature fall-back method for |
| 51 | an otherwise unsupported unwrapped method. Only applicable if |
| 52 | `--class` is also specified. It also requires use of the latest custom |
| 53 | subclass (signature) approach (see below for details on that), |
| 54 | as these plain methods are not "activated" in case of legacy approach |
| 55 | (for backwards compatibility). |
| 56 | |
| 57 | * `--expected`: |
| 58 | Use an error return type based on [std::expected](http://wg21.link/p0323) proposal |
| 59 | (as opposed to throwing exception). |
| 60 | |
| 61 | * `--dl`: |
| 62 | Use dlopen/dlsym to generate (most) calls rather than usual "direct" calls. |
| 63 | As such, a great many calls might then fail at runtime. So, if combined |
| 64 | with `--expected` all those calls will use the above error return type. |
| 65 | |
| 66 | * `--const-method`: |
| 67 | Mark (almost) all generated methods in generated wrappers as `const`. |
| 68 | Alternatively, perhaps more recommended, see also the helper `gi:cs_ptr` type. |
| 69 | |
| 70 | * `--class-args` _MIN_OPTIONAL_: |
| 71 | If >= 0, minimum number of non-required arguments that triggers generation of a |
| 72 | `CallArgs` signature variant (see below for details). |
| 73 | |
| 74 | * `--basic-container`: |
| 75 | Also generate a collection signature for an input collection of basic type |
| 76 | (e.g. `int`, etc). See below for some details and discussion. |
| 77 | |
| 78 | * `--output-top`: |
| 79 | Also generate convenience `.cpp` and `.hpp` files in root output directory |
| 80 | per namespace, as may be useful for some build tool setups. |
| 81 | |
| 82 | * `--only-changed`: |
| 83 | Disable overwriting (and timestamp update) of unchanged existing output file. |
| 84 | |
| 85 | * `--dump-ignore`: |
| 86 | (only if compiled with embedded ignore) Dumps embedded ignore data. |
| 87 | |
| 88 | ## ENVIRONMENT |
| 89 | |
| 90 | In stead of command-line options, environment variables can also be used. Note, |
| 91 | however, that options are still taken into account even when variables have |
| 92 | been set. The following environment variables are considered, and have the same |
| 93 | meaning as the corresponding command-line option: |
| 94 | |
| 95 | `GI_DEBUG`, `GI_IGNORE`, `GI_SUPPRESSION`, `GI_GEN_SUPPRESSION`, `GI_OUTPUT`, |
| 96 | `GI_CLASS`, `GI_CLASS_FULL`, `GI_EXPECTED`, `GI_DL`, `GI_GIR_PATH` |
| 97 | |
| 98 | In addition to the above, `GI_GIR` can specify a colon-separated lists of GIRs |
| 99 | (specified as on command-line). `XDG_DATA_DIRS` is also used as additional |
| 100 | source of directories to search for GIRs (within a `gir-1.0` subdirectory). |
| 101 | |
| 102 | |
| 103 | ## BACKGROUND |
| 104 | |
| 105 | ### API v2 |
| 106 | |
| 107 | Note that v2 API is somewhat different than previous API, so some porting of |
| 108 | existing code may be needed. See also later section for a rationale and |
| 109 | discussion on changes. |
| 110 | |
| 111 | The generated code provides a straight binding as specified by the annotations, |
| 112 | so everything is pretty much where expected, such as methods within classes |
| 113 | in turn within namespaces. For example, all `GObject` types are within |
| 114 | namespace `gi::repository::GObject`. With that in mind, it should be easy |
| 115 | to use and navigate in generated code, along with following comments: |
| 116 | |
| 117 | * As customary, anything within a `detail` or `internal` namespace is not meant |
| 118 | for public use and subject to change. The top-level gi namespace defines |
| 119 | a few things that make up public API which is meant to be stable |
| 120 | (though at this stage of maturity no full guarantee is provided). |
| 121 | |
| 122 | * Some generated code may have `_` (underscore) appended to it simply to avoid |
| 123 | clashing with a reserved keyword (or a preprocessor definition). It has |
| 124 | no special (reserved) meaning otherwise. |
| 125 | |
| 126 | * However, anything with leading underscore (if encountered) should be considered |
| 127 | as internal (and not meant for public API). |
| 128 | |
| 129 | In overall, the generated code is very lightweight and clear, easily understood |
| 130 | and with little runtime overhead, as also illustrated by the following |
| 131 | overview of wrappers for various kinds of types. Note that almost all of |
| 132 | them essentially wrap a pointer and therefore should be checked for validity |
| 133 | prior to many uses as with any "smart pointer" |
| 134 | (e.g. using provided `operator bool()`). |
| 135 | |
| 136 | **Objects.** |
| 137 | A GObject is a single pointer along with class code that manages a single |
| 138 | refcount (including decrement upon destruction). The refcount it manages is |
| 139 | either received/taken from a `full` transfer, or `ref_sink`'ed (in case of |
| 140 | `none`/`floating` transfer, see also discussion in subsequent section on the |
| 141 | intricacies of the latter and theoretical edge cases). |
| 142 | |
| 143 | **Boxed Types.** |
| 144 | Similarly, but with a minor twist, wrappers for a boxed GType `MyBox` come in 2 |
| 145 | kinds; an owning `MyBox` and a non-owning `MyBox_Ref`. In both cases, the |
| 146 | wrapper is again a single pointer with some suitable/applicable helper methods. |
| 147 | The former essentially acts a "unique ptr" (with `g_boxed_free` deleter) whereas |
| 148 | the latter acts as a "naked ptr/reference" (without any ownership or cleanup). |
| 149 | Obviously, for the latter case, all the usual caution regarding dangling |
| 150 | references (etc) applies. The latter are used for transfer `none` cases and |
| 151 | the former in transfer `full` situations. In case a safe "reference" needs to |
| 152 | be kept around (e.g. in some member), then a `_Ref` can be `.copy_()`'d (which |
| 153 | uses `g_boxed_copy`) to an owning wrapper. The above semantics also imply that |
| 154 | the owning wrapper is move-only (and again `.copy_()` yields a copy). However, |
| 155 | there are quite some cases where a boxed copy is based on a refcount (which also |
| 156 | preserves the box identity/pointer). Those cases have been specially marked (in |
| 157 | overrides) to make the owning wrappers copyable as well. Likewise, a `_Ref` of |
| 158 | such cases can be (implicitly) assigned/copied to an owning one (in each case |
| 159 | triggering a `g_boxed_copy` which is then known to be plain and cheap). |
| 160 | If desired, additional wrappers could be marked as copyable, in which case a |
| 161 | wrapper copy invokes a potentially more expensive (and non-identity preserving) |
| 162 | `g_boxed_copy`. Also, or alternatively, if `GI_ENABLE_BOXED_COPY_ALL` is |
| 163 | defined and truthy, then all boxed wrappers are copyable in that way. |
| 164 | |
| 165 | **Record Types.** |
| 166 | Plain records (i.e. structs with no registered GType) are handled in a similar |
| 167 | fashion, with `g_free` as "deleter" (and without any copy support). Since no |
| 168 | lifecycle resource management (construction, destruction) is available for such |
| 169 | types, there are (quite some) limitations to what code generation or binding can |
| 170 | do here (see also discussion in corresponding section). |
| 171 | |
| 172 | **Strings.** |
| 173 | A string (e.g. `char*`) is also regarded and wrapped in a similar way. That is, |
| 174 | a `gi::cstring` wraps (and owns and manages) a C `char*` and `gi::cstring_v` is |
| 175 | the corresponding non-owning variant. Obviously, the former bears resemblance |
| 176 | to `std::string` whereas the latter to `std::string_view`. In fact, as there is |
| 177 | no real definitive "string API" (in C or glib), their API is fairly similar |
| 178 | (though not guaranteed identical) to the `std` counterparts. Also, various |
| 179 | conversions from/to `std` counterparts should allow for convenient type |
| 180 | interchange. Additional integration with other string types is also possible by |
| 181 | further specialization of `gi::convert::converter` (see `gi/string.hpp` source |
| 182 | for details). |
| 183 | |
| 184 | **Collections**. |
| 185 | That is, `GList`, `GSList`, `GPtrArray`, `GHashTable` or plain arrays |
| 186 | (zero-terminated or not). Similar to `std` container, each collection wrapper |
| 187 | is a templatized `gi::Collection` type, with (a.o.) a type parameter for the |
| 188 | contained type. As with some of the above types, such wrappers come in an |
| 189 | owning and non-owning variants, as specified by another (type) parameter and |
| 190 | obtained from annotations, i.e. transfer `none`, transfer `container` or transfer |
| 191 | `full`. Note that the "ownership" specifies both ownership of the container and |
| 192 | of the contained elements. Of course, where needed, code generation will select |
| 193 | and specify the proper type (e.g. as function parameter). Following aspects |
| 194 | are worth mentioning; |
| 195 | |
| 196 | * Templatized constructors and conversion operators support construction |
| 197 | from/of and assignment from/to (e.g.) `std` container types. Likewise |
| 198 | so for "similar" (duck-ed) types, where "similar" refers to member types and |
| 199 | constructor signatures. |
| 200 | |
| 201 | * A (`std`) container-ish API is also provided, though neither identical |
| 202 | nor fully compatible (a.o. due to limitations of the C wrappee's API). |
| 203 | However, the `none` (ownership) variant is considered read-only and so |
| 204 | it does not provide any "modification" API parts and only a `const` iterator. |
| 205 | As almost no wrapper methods are `const`, an `auto p : coll` (range-for) |
| 206 | pattern is recommended (wrappers are cheaply copied). Other variants do |
| 207 | support modification as well as iteration that allows for a `auto &p : coll` |
| 208 | pattern (if so desired). In particular, this applies to the `full` variant, |
| 209 | which is the recommended one for "standalone" use (as container), as it |
| 210 | safely manages ownership of both itself and elements. |
| 211 | |
| 212 | * Wrappers of refcounted collections (`GPtrArray`, `GHashTable`) are |
| 213 | otherwise similar to object wrappers. So they *always* manage a refcount (and |
| 214 | are copyable) regardless of ownership variant (none, etc). The other wrappers |
| 215 | are similar to boxed wrappers, e.g. copyable in `none` variant, but otherwise |
| 216 | assume unique ownership and are non-copyable. |
| 217 | |
| 218 | * A `gi::CollectionParameter` may also used by code generation for a function |
| 219 | input parameter. In case of `none` ownership, this type/instance will |
| 220 | temporarily hold ownership of a collection that may be created by conversion |
| 221 | from another container. Temporarily here refers to the duration of the call |
| 222 | during which the parameter instance exists. It is not (and should not be) |
| 223 | used elsewhere. |
| 224 | |
| 225 | * For an input collection parameter of basic type (e.g. `int`), the |
| 226 | original C signature is typically used. That is, 2 parameters (`int*` and |
| 227 | `gsize`). The rationale here is that the same signature may also occur for an |
| 228 | output collection (of specified input size). Preserving the original signature |
| 229 | ensures that it can be used whether or not the annotation is correct. The |
| 230 | latter may not be the case as these APIs are typically "low-level" (e.g. involve |
| 231 | some buffers), and as such are often not considered by "scripted binding". It is |
| 232 | also an efficient and clear API as any buffer's "location" (e.g. `std::vector` |
| 233 | or otherwise) can easily be provided by means of these 2 parameters. |
| 234 | However, if desired and specified by `--basic-container` option, then an |
| 235 | additional collection-based signature is generated as well. |
| 236 | |
| 237 | In short, one can choose to work with `std` types and convert to |
| 238 | collection wrappers upon function call/return, but for simple cases (or beyond), |
| 239 | the collection wrapper might well serve (without conversion). |
| 240 | |
| 241 | **Plain Types.** |
| 242 | Various enum, (static) method, functions, typedef (for callback) fill in the |
| 243 | rest. |
| 244 | |
| 245 | **Functions.** |
| 246 | Functions that involve the usual `GError` return pattern are wrapped in a few |
| 247 | ways. On the one hand, in a straight way, where the error is a (wrapped error) |
| 248 | output parameter. Alternatively, the error parameter is removed from the |
| 249 | signature. In that case it is "returned" by either throwing the (wrapped) error |
| 250 | (which is also a `std::exception` subclasss), or by returning a suitable |
| 251 | `expected` type (with the wrapped error type as error type). While throwing is |
| 252 | default behaviour, the latter can be requested using `--expected` option. |
| 253 | |
| 254 | In case of a `GError` in (function) callback or virtual method signature, it is |
| 255 | always retained as a (wrapped) error output parameter and preferably used to |
| 256 | report an error that way. Alternatively, an exception can be thrown, preferably |
| 257 | then a `GLib::Error` instance. Callback wrapping code will catch any exception |
| 258 | and report (to `C` caller) using `GError` output along with a zero-initialized |
| 259 | return value, which is likely but not necessarily a good choice. |
| 260 | |
| 261 | Note, however, that the aforementioned `catch` only applies if exception support |
| 262 | is enabled. Auto-detection of this should usually work, but if needed can be |
| 263 | specified by defining `GI_CONFIG_EXCEPTIONS` explicitly (truth/falsy). |
| 264 | |
| 265 | If a function has (non-GError) output parameters, then there is a signature |
| 266 | where these outputs are parameters (as in the plain C case) and another variant |
| 267 | where these are incorporated in the return value, which may then become a |
| 268 | `std::tuple<>` type. |
| 269 | |
| 270 | If so configured, some so-called `CallArgs` variations may also be generated. In |
| 271 | this case, (roughly) a custom `xyz_CallArgs` struct type is generated (for each |
| 272 | function `xyz`) with members corresponding to the function arguments along with |
| 273 | a function with 1 argument (of that custom struct type). In case of many |
| 274 | (optional) arguments, this argument could be specified using designated |
| 275 | initializer syntax, thereby allowing a sort-of "call by keyword". Again, there |
| 276 | are variations with output parameters as return value or not. Besides some |
| 277 | potential advantages, there are also some drawbacks, however. First and |
| 278 | foremost, when using the member names in designated initializers, these names |
| 279 | then become essentially part of the API, although the name's origin as |
| 280 | plain C function parameter does not provide stability guarantee. Also, |
| 281 | suffice it to say a great many struct types can be generated this way. This could |
| 282 | be mitigated by employing a suitable "generation level", e.g. 2. In that case, |
| 283 | only functions that have at least 2 (or more) non-required arguments will have |
| 284 | such a custom type and signature generated. |
| 285 | |
| 286 | **Subclasses and Interfaces.** |
| 287 | Some additional specifications on how subclasses and interfaces are mapped |
| 288 | may also be in order. A subclass in the GObject world is directly mapped as a |
| 289 | subclass in the C++ binding. However, if a GObject implements an interface, the |
| 290 | generated class does not inherit from the interface's (generated) class. This |
| 291 | is mostly of a matter of implementation choice (and to ensure its lightweight |
| 292 | simplicity). However, knowledge of implemented interfaces is not always |
| 293 | available at compile time, e.g. in case of dynamically loaded GStreamer |
| 294 | elements (though it is more likely in case of Gtk hierarchy). Since there would |
| 295 | be no inheritance in the dynamic case, a consistent choice is not to have it at |
| 296 | any time. However, for ease of use, some helper code is generated when an |
| 297 | implemented interface is known at generation/compile time, as illustrated in |
| 298 | the following snippet from an example |
| 299 | |
| 300 | // use a cast if not known, either to a class or interface |
| 301 | auto bin = gi::object_cast<Gst::Bin>(playbin_); |
| 302 | // known at compile time; overloaded interface_ method |
| 303 | auto cp = bin.interface_ (gi::interface_tag<Gst::ChildProxy>()); |
| 304 | |
| 305 | |
| 306 | ### SUBCLASS IMPLEMENTATION API |
| 307 | |
| 308 | There may be times when one would want to make a custom subclass of GObject, or |
| 309 | of some Gtk widget. In the same vein, (current) implementation choices imply |
| 310 | that one should not simply inherit from `Gtk::Window`. Part of the motivation |
| 311 | here is that such subclassing depends on style and setting, i.e. it is rather |
| 312 | rare when in a GStreamer setting, but less so in e.g. Gtk. As such, the |
| 313 | possibly rare cases should not burden or complicate the basic wrapping usecase. |
| 314 | |
| 315 | Before going into the details of "how", let's first consider what a "subclass" |
| 316 | actually means in this context. It will probably involve a (C++) (sub)class of |
| 317 | some generated class (related to a GObject class type) with potentially |
| 318 | extra/custom properties and signals. In particular, the latter implies it also |
| 319 | involves a new `GType` that defines a subtype (of the aforementioned GObject |
| 320 | class type). An instance of such class/type then consists of a C++ instance |
| 321 | that is 1-to-1 associated with a GObject instance of the custom defined (sub) |
| 322 | `GType`. |
| 323 | |
| 324 | In turn, this leads to (at least, for now) 2 possible ways to create instances; |
| 325 | |
| 326 | * triggered on C++ side, in the usual way through a constructor. The bottom |
| 327 | of the constructor chain registers a custom `GType` (if still needed), creates |
| 328 | an instance (`g_object_new()`) and associates it (with the C++ instance). |
| 329 | |
| 330 | The advantage is that standard use of C++ constructor applies. The downside |
| 331 | is that the defined `GType` can not be (safely) used in the GObject |
| 332 | (eco)system, as any `g_object_new()`'d instance is incomplete (as it lacks a |
| 333 | C++ instance). |
| 334 | |
| 335 | * triggered on C-side by `g_object_new()`. In this case, the registered type's |
| 336 | custom (GObject) `constructor` first delegates to parent constructor to create |
| 337 | a GObject subtype instance and then `new`'s a C++ object, and again the |
| 338 | bottom of the constructor chain associates it with created GObject instance. |
| 339 | |
| 340 | In this case, an instance has to be created based on `GType`. However, this |
| 341 | type can be safely used in any `GType` based factory system, e.g. when |
| 342 | referenced (by name) in XML/UI file or (by number) in a GStreamer plugin |
| 343 | factory. |
| 344 | |
| 345 | In summary, (up to) 2 different ways to create objects, and so (up to) 2 |
| 346 | different custom `GType` that can be defined by a "subclass". The latter one |
| 347 | is more recent and is also the recommended approach as instances are always |
| 348 | properly created. Also, if desired, some additional helper `new_()` member |
| 349 | can be defined that acts as a surrogate constructor. |
| 350 | |
| 351 | So, how to subclass then? By a slight twist by using the `impl` namespace |
| 352 | variations, as in following excerpt from an example: |
| 353 | |
| 354 | class TreeViewFilterWindow : public Gtk::impl::WindowImpl |
| 355 | { |
| 356 | // ... |
| 357 | public: |
| 358 | // Assume (hypothetically) that Window also implements FakeInterface |
| 359 | // with a set_focus method, then a compilation failure will be triggered (as |
| 360 | // it can no longer be detected whether set_focus is defined in this class). |
| 361 | // Then the following inner struct is needed to resolve so manually; |
| 362 | struct DefinitionData |
| 363 | { |
| 364 | // the last parameter specifies whether the method is defined |
| 365 | // (which may well be false in all class/interface cases if not defined) |
| 366 | GI_DEFINES_MEMBER(WindowClassDef, set_focus, true) |
| 367 | GI_DEFINES_MEMBER(FakeInterfaceDef, set_focus, false) |
| 368 | }; |
| 369 | // NOTE for the auto-detection to work, the methods must be accessible |
| 370 | // so either they should be defined public, or (e.g.) WindowClassDef |
| 371 | // must be declared friend, or the above manual resolution can be used. |
| 372 | |
| 373 | // this (super)constructor signature leads to a C++ side type |
| 374 | TreeViewFilterWindow () : Gtk::impl::WindowImpl (this) |
| 375 | { |
| 376 | // ... |
| 377 | } |
| 378 | |
| 379 | // this (super)constructor signature leads to a C-side type |
| 380 | // NOTE InitData is not (easily) instantiated, |
| 381 | // so this constructor is only used by the internal C-side mechanics |
| 382 | TreeViewFilterWindow (const InitData &id) |
| 383 | : Gtk::impl::WindowImpl (this, id, "TreeViewFilterWindow") |
| 384 | |
| 385 | void set_focus_ (Gtk::Widget focus) noexcept override |
| 386 | { |
| 387 | } |
| 388 | |
| 389 | // the above constructor is also re-used during (C-side) type registration |
| 390 | // (in that case with an "empty" id and no associated GObject setup) |
| 391 | // that can avoided by providing a separate ... |
| 392 | static GType get_type_() |
| 393 | { |
| 394 | // no interfaces, properties or signals to declare |
| 395 | return register_type_<TreeViewFilterWindow>("TreeViewFilterWindow", 0, {}, {}, {}); |
| 396 | } |
| 397 | }; |
| 398 | |
| 399 | // create an instance of (either) type |
| 400 | // it prefers the latter C-side type, if supported, and supports extra arguments |
| 401 | // (a second template parameter allows for specific selection, |
| 402 | // see code comments and examples for details) |
| 403 | gi::make_ref<TreeViewFilterWindow>() |
| 404 | |
| 405 | Parent (class or interface) methods can then be overridden or implemented |
| 406 | in the usual way by simply defining them in the subclass. It is also possible |
| 407 | to define custom signal and properties in the subclass, as illustrated in the |
| 408 | `gobject.cpp` example. As mentioned, the inner `DefinitionData` struct in the |
| 409 | above fragment is usually not needed, but only in case of conflict/duplication |
| 410 | of class/interface member(s). |
| 411 | |
| 412 | Since this is considered an optional feature, the `impl` parts are not generated |
| 413 | by default, but only if the `--class` option is specified. Since the virtual |
| 414 | methods share some similarities with callbacks they are also subject to some |
| 415 | limitations (see corresponding section). As such, it may happen that some |
| 416 | virtual methods do not have a wrapper. If the `--class-full` option is |
| 417 | specified, then a passthrough virtual method (with C signature as-is) is then |
| 418 | generated instead, which can then be overridden and implemented as a fallback. |
| 419 | So the custom type registration (that happens behind the scenes) can then still |
| 420 | be used, albeit at the expense of dealing with a plain C signature and types |
| 421 | (which is similar to directly calling a C function as a fallback if no wrapper |
| 422 | function was generated for some reason). |
| 423 | |
| 424 | It is also a fairly advanced feature, with various aspects not immediately |
| 425 | obvious. For example, the resulting "instances" have "2 sides"; there is C++ |
| 426 | object instance as well as an associated (derived) GObject instance (which |
| 427 | internally refer to each other in 1-to-1 association ). In particular, it |
| 428 | follows that their destruction must be closely coordinated. This is potentially |
| 429 | tricky as the GObject side is traditionally reference-counted, whereas the C++ |
| 430 | object could be anything (stack-allocated or otherwise). The latter can be |
| 431 | stack-allocated if it is ensured that there is no lingering reference in the |
| 432 | GObject world. So, it depends on the use-case as to how to proceed. But in |
| 433 | overall, it is probably recommended to manage lifetime and ownership based on |
| 434 | GObject (side) reference count. The `gi::make_ptr` and `gi::ref_ptr` helpers |
| 435 | can be helpful in this regard. |
| 436 | |
| 437 | There are also situations where the C API (implementation) involves some |
| 438 | "low-level tricks" which do not port over in a simple or straight way (e.g. |
| 439 | `GtkBuilder`). Those are likely in need of some custom overrides or extensions |
| 440 | (see also below) which may or may not already be provided for some particular |
| 441 | API/situation. It is highly advised to browse provided overrides and |
| 442 | extensions and/or consult the closest relevant related example |
| 443 | (which usually showcases what is available, along with additional explanations). |
| 444 | |
| 445 | |
| 446 | ### CODE LAYOUT AND BUILD SETUP |
| 447 | |
| 448 | The generated code is written to the top-level with the following layout. |
| 449 | Each GIR namespace has a corresponding subdirectory, say `ns` |
| 450 | (and also a C++ namespace, `cppgir::repository::ns`). The top-levels |
| 451 | headers for a namespace are then: |
| 452 | |
| 453 | * `ns.hpp`: |
| 454 | a regular header providing the namespace's declarations. |
| 455 | It will also include the dependent namespaces' top headers. |
| 456 | If the macro `GI_INLINE` is defined, then it will also include ... |
| 457 | * `ns_impl.hpp`: |
| 458 | contains the definitions corresponding to the declarations. |
| 459 | Normally, this would be a `.cpp` file, but as they might be included directly |
| 460 | in the inline case, they have been named `xxx_impl.hpp` instead. |
| 461 | * `ns.cpp`: |
| 462 | this merely includes `ns_impl.hpp` and is as such no different |
| 463 | than the latter, except for more traditional naming. |
| 464 | Compiling this file in the non-inline case provides all the definitions |
| 465 | for the namespace in the resulting object file. |
| 466 | * `*.cppm`; module wrappers, see next subsection for details. |
| 467 | |
| 468 | So, in summary, it comes down to setting up the build system to build each of |
| 469 | the namespaces' `.cpp`, as is also done in this repo's CMake build setup. |
| 470 | There is one other shortcut build setup that is illustrated by the `gtk-obj.cpp` |
| 471 | example file, which includes all definitions (recursively): |
| 472 | |
| 473 | #define GI_INCLUDE_IMPL 1 |
| 474 | #include <gtk/gtk.hpp> |
| 475 | |
| 476 | Note, however, this is only possible if there is exactly 1 top-level namespace, |
| 477 | as doing this for several namespaces will lead to duplicate definitions. |
| 478 | |
| 479 | Some items (functions, types) may be marked as deprecated (in source code). |
| 480 | while still present in GIR data. Wrappers will still be generated and |
| 481 | `pragma` are issued to avoid warnings that might otherwise occur. |
| 482 | Generic `gi` support tries to avoid using deprecated code. There is, however, |
| 483 | one exception regarding the use of `g_object_newv`, which is deprecated |
| 484 | but may have to be used if support for an older GLib is required. |
| 485 | This can be arranged by defining `GI_OBJECT_NEWV` (and the deprecation |
| 486 | warning should also be silenced when dealing with newer version). |
| 487 | If the items are also marked deprecated in GIR data, then these are skipped |
| 488 | by default. However, if the string `deprecated:<NAMESPACE>:<VERSION>` |
| 489 | matches (a regexp) in specified ignore data/files, then deprecated items |
| 490 | will be considered for the namespace in question, after being checked as |
| 491 | usual against the ignore list. |
| 492 | |
| 493 | If you have specified the `--class` option, then the generated code will |
| 494 | possibly contain classes that inherit from several classes (representing |
| 495 | interfaces). Since various interfaces may have overlapping member names, this |
| 496 | might trigger compilation warnings. These are not suppressed by default, as you |
| 497 | may need to be made aware of this. However, if it does no harm in your |
| 498 | particular case, then defining `GI_CLASS_IMPL_PRAGMA` should arrange for proper |
| 499 | suppression. |
| 500 | |
| 501 | The generated code may be quite extensive and so it may present a "heavy build". |
| 502 | Other than that the above allows for a number of different build setups, |
| 503 | `cppgir` tries not to impose any particular approach. In particular, standard |
| 504 | tried-and-tested build optimizations can be applied, such as precompiled headers |
| 505 | (with some good results, as reported in |
| 506 | [issue #99](https://gitlab.com/mnauw/cppgir/-/issues/99)). |
| 507 | |
| 508 | |
| 509 | **C++ Module support** |
| 510 | |
| 511 | At this time of writing, module support is still new-ish in compilers |
| 512 | and (not in the least) build tools. Unfortunately, all major compilers also |
| 513 | take a different approach in handling these wrt command-line argument, source |
| 514 | file extension or binary output. Note that this also likely complicates any |
| 515 | `compile_commands.json` based tooling (e.g. LSP server as used by IDEs) along |
| 516 | with other issues as outlined in |
| 517 | [this post](https://nibblestew.blogspot.com/2023/12/even-more-breakage-in-c-module-world.html) |
| 518 | and originally raised |
| 519 | [long ago](https://vector-of-bool.github.io/2019/01/27/modules-doa.html). |
| 520 | |
| 521 | By comparison, precompiled headers are long since well supported, so these may |
| 522 | be a more recommended alternative approach. |
| 523 | |
| 524 | Failing that, a next natural fit might be "header units" (in module spec sense). |
| 525 | Unfortunately, compiler setup here varies somewhat and build tool support may be |
| 526 | limited. |
| 527 | |
| 528 | So, a next step is a pure/real module. Unfortunately, "core gi" can not be |
| 529 | provided in that form; |
| 530 | |
| 531 | * in addition to code, it also "exports" some macros, which can not really be |
| 532 | `export`'ed or `import`'ed (only from a "header unit") |
| 533 | * the core is somewhat intertwined with basic types from GObject, |
| 534 | e.g. some code-generated types are forward declared (which satisfies |
| 535 | for their purposes in "core gi"). However, forward and real declaration |
| 536 | can not pass module boundary. |
| 537 | |
| 538 | But "core gi" combined with (generated) GLib and GObject can be wrapped |
| 539 | in a module (along with a separate "macro API header", `gi_inc.hpp`). |
| 540 | |
| 541 | Again, `cppgir` does not impose a particular module layout/setup, but provides |
| 542 | the basic parts and pieces to do so. The generated code also provides a few |
| 543 | example module wrappers (with no stability guarantee), also see `gst.cpp` and |
| 544 | `gtk.cpp` examples for possible usage details; |
| 545 | |
| 546 | * `ns.cppm` (exports `gi.repo.ns`); |
| 547 | module that wraps/provides `ns` (inline) code, so a typical compilation |
| 548 | produces `.o` code of `ns` and a BMI/CMI that exports `ns` declarations |
| 549 | * `ns_rec.cppm` (exports `gi.repo.ns.rec`); |
| 550 | module that wraps/provides `ns` and all (recursive) dependencies, so a |
| 551 | typical compilation produces `.o` code of `ns` and dependencies, along |
| 552 | with a BMI/CMI with corresponding declarations. |
| 553 | |
| 554 | The above have been tested with gcc-15 and clang-18 with some varied measure of |
| 555 | success (apparently, GCC fails to link the non-recursive approach). They each |
| 556 | come with an extra "knob"; if `GI_MODULE_EXTERN` is defined, then the module |
| 557 | purview is essentially `extern "C++" { ... }`. So all declarations are then |
| 558 | attached to global module, as opposed to the named module, and as such do not |
| 559 | incur any modified ABI linkage (`@M`) (so it may be recommended). |
| 560 | |
| 561 | Other variations are likely possible, e.g. module partitions, separate |
| 562 | module implementation, etc. |
| 563 | |
| 564 | |
| 565 | ### OVERRIDING OR EXTENDING |
| 566 | |
| 567 | It is possible to add functions or methods or override existing names (by |
| 568 | effect of name hiding). To this end, the generated code contains various |
| 569 | 'optional include hooks' using the `__has_include` directive. This way, code in |
| 570 | externally supplied (include) files can be inserted into the class definition |
| 571 | chain. There are roughly 3 such 'hook points': |
| 572 | |
| 573 | * **initial setup**: |
| 574 | this part is (conditionally) included before the namespace's C headers are included. |
| 575 | This allows specifying define's to tweak subsequent headers or to add |
| 576 | headers that also need to be include'd, and which may not have been specified |
| 577 | in the GIR. |
| 578 | |
| 579 | * **class definition**: |
| 580 | these hooks allow extending the wrapped class with new or tweaked methods |
| 581 | |
| 582 | * **global extra definitions**: |
| 583 | these are included after all generated code, and supports adding of new global |
| 584 | functions, typedef's, type trait helper declarations, ... |
| 585 | |
| 586 | The reader is invited to examine the default overrides in this repo as well as |
| 587 | the generated code to see how this fits together based on a simple naming |
| 588 | scheme and use of macros. In particular, see the provided `GLib` overrides. |
| 589 | Suffice it to add that the `_def` suffix refers to 'default' as supplied by |
| 590 | this repo and which are installed alongside the common headers. The |
| 591 | corresponding non-suffixed filenames should be used by project specific custom |
| 592 | additions. |
| 593 | |
| 594 | |
| 595 | ### CODE GENERATION |
| 596 | |
| 597 | It might be necessary to exclude a GIR entry from processing, either because it |
| 598 | is a basic type handled by custom code (e.g. `GObject`, `GValue`, ...) or |
| 599 | because of a faulty annotation. The latter can be a glitch in the annotation |
| 600 | itself, or one that actually refers to a symbol in a non-included private |
| 601 | header. The exclusion can be directed by so-called ignore files, and at least |
| 602 | one such is supplied as a system default ignore containing known and essential |
| 603 | cases to exclude (and without which code generation would not produce valid |
| 604 | code). Such a file consists of lines of regular expressions (`#` commented |
| 605 | lines are ignored). At generation time, each symbol is turned into a |
| 606 | `<NAMESPACE>:<SYMBOLKIND>:<SYMBOL>` string, and excluded if it matches one of |
| 607 | the lines' regular expression. So, for instance, `GObject:record:Value` |
| 608 | prevents processing of `GValue`, since there is already special-case code for |
| 609 | that in the common header code. Further expression examples are found in the |
| 610 | default ignore file. Additional files can be specified by the `--ignore` |
| 611 | option. |
| 612 | |
| 613 | As each entry is processed, some notification may be given regarding a |
| 614 | perceived inconsistency in an annotation or an unsupported case (see also [BUGS |
| 615 | AND LIMITATIONS](#bugs-and-limitations)). When the reported cases have been |
| 616 | (manually) checked and considered harmless, the corresponding notices can be |
| 617 | suppressed by specifying suppression files to `--suppression`. The format of |
| 618 | such files is the same as ignore files, except that a match then simply serves |
| 619 | to decrease reporting verbosity. Such a file could be hand-crafted, but it can |
| 620 | also be auto-generated by a run when specifying `--gen-suppression`. |
| 621 | |
| 622 | Besides excluding problematic GIR parts, one might also consider solutions to |
| 623 | some problematic GIRs used by other projects, such as fixed GIRs maintained by |
| 624 | [gtk-rs](https://gtk-rs.org/gir/book/tutorial/finding_gir_files.html#gtk-dependencies) |
| 625 | in the referenced [repo](https://github.com/gtk-rs/gir-files). |
| 626 | |
| 627 | ### (RATIONALE OF) v2 CHANGES |
| 628 | |
| 629 | Consider the following python session using gobject-introspection: |
| 630 | |
| 631 | >>> import gi |
| 632 | >>> gi.require_version('Gst', '1.0') |
| 633 | >>> from gi.repository import Gst |
| 634 | >>> Gst.init(None) |
| 635 | >>> c = Gst.caps_from_string('video/x-raw') |
| 636 | >>> c.get_structure(0) |
| 637 | <Gst.Structure object at 0x7fe284096760 (GstStructure at 0x1bb4420)> |
| 638 | >>> c.get_structure(0) |
| 639 | <Gst.Structure object at 0x7fe2840b5d00 (GstStructure at 0x1bb43a0)> |
| 640 | |
| 641 | What happens here? A different `GstStructure*` is created each time, even |
| 642 | though the same one is returned (by C code) in each case. The python binding |
| 643 | here has no other choice than to use `g_boxed_copy()` on the transfer `none` |
| 644 | return value. If it would not, it would be carrying around an unguarded/unowned |
| 645 | and hence potentially dangling pointer (in some `PyObject` wrapper), which is |
| 646 | a definite no-go in a scripted setting that must always ensure valid objects. |
| 647 | |
| 648 | v1 API followed a similary "scripted" style approach where all objects/pointers |
| 649 | should always be safe and valid, with (roughly) `std::shared_ptr` in place of |
| 650 | `PyObject`. Of course, also then with similar (copy) effects as in the above |
| 651 | excerpt and in e.g. [issue #32](https://gitlab.com/mnauw/cppgir/-/issues/32). |
| 652 | |
| 653 | v2 now follows a different approach. After all, C++ is much closer to C, and it |
| 654 | is customary to mind about (potentially dangling) references and such, and where |
| 655 | and how (not) to use e.g. `std::string_view`. And so while types/objects are |
| 656 | now no longer always "owning" (and as such always safe), the type conventions do |
| 657 | clearly specify whether or not they do (own). As such, standard C++ practices |
| 658 | should handle what v2 API provides, while avoiding superfluous and potentially |
| 659 | surprising copies or any other "automagic". In particular, the v2 bindings |
| 660 | are therefore even more "tight and direct" than before, with a typical wrapper |
| 661 | being only a cast away from the wrappee (and matching in size and semantics). |
| 662 | |
| 663 | **Migration.** |
| 664 | In practice, only limited changes have been needed in the included examples. |
| 665 | Of course, your mileage may vary, depending on usage of "boxed types" as well |
| 666 | as use of (type deduction) `auto` versus explicit type specification. |
| 667 | Some `_Ref` types may have to be used instead here or there, as well as possibly |
| 668 | some `std::move` on "owning" variants (unless overall boxed copy is enabled). |
| 669 | For reasons of consistency and to avoid collision with generated methods, |
| 670 | some more "custom methods" may have had `_` appended |
| 671 | (e.g. `CBoxed::allocate_()`). |
| 672 | |
| 673 | |
| 674 | ## BUGS AND LIMITATIONS |
| 675 | |
| 676 | The generated code's coverage is pretty good and comfortably serves most |
| 677 | cases that arise in practice as also illustrated by the examples. |
| 678 | Nevertheless, the following should be mentioned: |
| 679 | |
| 680 | **Callback types.** |
| 681 | Only callback types that have an explicit `user_data` |
| 682 | parameter are supported. That includes (fortunately) cases such as connecting |
| 683 | to a signal, or a `GstPadProbeCallback`, though a `GstPadChainFunction` is |
| 684 | excluded. The reason is a technical one; the `user_data` parameter is used to |
| 685 | pass data used by callback wrapper code. A typical (script) runtime binding |
| 686 | handles this using [libffi](https://github.com/libffi/libffi)'s closure API. In |
| 687 | effect, a little bit of executable code is then generated at runtime, and the |
| 688 | address of that code then essentially serves as surrogate `user_data` that can |
| 689 | carry extra meta-data for use by the runtime. This could also be employed here |
| 690 | to lift the `user_data` limitation, it would take a bit extra work, but would |
| 691 | more importantly then also incur an additional dependency. |
| 692 | |
| 693 | **Callback handling.** |
| 694 | Even if `user_data` is present, other aspects of a callback signature |
| 695 | may not be supported (at this time), e.g. certain (sized) array parameters. |
| 696 | However, few (if any) of such actual cases are known at this time. |
| 697 | Note that both signals and virtual methods are somewhat similar to a callback |
| 698 | and as such share similar limitations. |
| 699 | |
| 700 | Whereas the above items could (in theory) be resolved, the following are more |
| 701 | inherent limitations (by the very context and nature of e.g. annotations). |
| 702 | Fortunately, though, the practical impact is fairly limited (if any). |
| 703 | |
| 704 | **const handling.** In C++, this is a Bigger Thing. For instance, a simple |
| 705 | 'getter' should preferably be marked const. However, on the original C-side of |
| 706 | things, only very limited consideration is given to this. Even if there is some |
| 707 | `const`, it is not treated with all that much respect, e.g. |
| 708 | `g_value_take_boxed` starts `const` but it is merrily cast away along the way. |
| 709 | As such, there is not much to find on const-ness in annotation data, and so no |
| 710 | point in inventing any. Rather, the focus is simply on getting the proper |
| 711 | function calls done along with automagic refcount and resource management (much |
| 712 | as any runtime binding would do, with no regard for const whatsoever in that |
| 713 | case). |
| 714 | |
| 715 | In particular, methods are usually not marked `const` either, as there is |
| 716 | similarly no (semantic) data to decide either way. As such, it is not |
| 717 | recommended to use `const` wrapper types. However, they may arise due to generic |
| 718 | templates or when captured in a lambda. In such cases, the helper (template) |
| 719 | type `gi::cs_ptr` may be useful, or alternatively one might set the option to |
| 720 | mark all code-generated methods as `const`. |
| 721 | |
| 722 | **Floating (into darkness).** |
| 723 | [Gobject docs](https://docs.gtk.org/gobject/floating-refs.html) mention the |
| 724 | following about floating references (i.e. transfer `floating`); |
| 725 | |
| 726 | > Floating references are a C convenience API and should not be used in modern |
| 727 | GObject code. Language bindings in particular find the concept highly |
| 728 | problematic, as floating references are not identifiable through annotations, |
| 729 | ... |
| 730 | |
| 731 | Indeed, by the time `floating` makes it into the parsed annotation, it has |
| 732 | become `none`. And in case of a "factory" `some_widget_new()`, `floating` |
| 733 | behaves more like `full` as the caller must "take ownership" to avoid a leak. So |
| 734 | a "floating" `none` is quite different from a "real" `none` (e.g. "getter" |
| 735 | method). But no way to know from annotation data. So, in case of `none`, an |
| 736 | object wrapper always `ref_sink()`s. If it was floating, it has taken suitable |
| 737 | ownership. If it was really none, then it is now managing an extra refcount. |
| 738 | And in either case, it will release/decrement upon destruction. Essentially, |
| 739 | this follows the recommendation given in referenced docs. In practice, it |
| 740 | actually Just Works. |
| 741 | |
| 742 | It gets really tricky when this is combined with e.g. lists. So what does `none` |
| 743 | mean in this case (in annotation)? In the worst case, the contained elements |
| 744 | might actually be floating, so one would have to go through the list and |
| 745 | `ref_sink` them all (un)conditionally? Suffice it to say, no such "automagic" |
| 746 | is handled/injected by any wrapper code. Fortunately, at this time there does |
| 747 | not seem to be such a "multiple factory" API. Even if there were, then in |
| 748 | practice the calling code is likely to loop over the list and access the |
| 749 | elements. The ensuing C++ wrappers (even if existing only briefly) would then |
| 750 | effectively `ref_sink()`, so again we are ok. And last but not least, by the |
| 751 | above quoted recommendation, there should be no such new tricky API coming |
| 752 | along. So, again, it Just Works. If needed, any such old or new API can and |
| 753 | should be handled by custom overrides. |
| 754 | |
| 755 | **Boxed (by darkness).** |
| 756 | This refers to so-called "plain records" which are "C structs" with no |
| 757 | registered `GType` (referred to as "C boxed" types in `cppgir` code), e.g. |
| 758 | `GOptionEntry` or `GstMapInfo`. While their fields may be described in |
| 759 | annotations, there is no information regarding the "ownership" of any data |
| 760 | (which may even vary upon context). In particular, also no way to create/free. |
| 761 | This corresponds with their frequent stack-allocated use in C code in typically |
| 762 | "low-level" API which is usually not considered "binding friendly". Based on |
| 763 | the mild assumption that 0-initialized data makes a valid instance, they are |
| 764 | treated somewhat similar to (GType) boxed types and as such can be used in some |
| 765 | limited (function call) situations. Any improvement beyond that is likely to |
| 766 | remain in the purview of overrides. |
| 767 | |
| 768 | |
| 769 | ### WORKAROUNDS |
| 770 | |
| 771 | As C++ allows direct mixing/calls with C, there are usually some fallback |
| 772 | workarounds when confronted with one of the limitations. First of all, |
| 773 | note that a C++ wrapper typically has e.g. a `gobj_()` method that |
| 774 | provides the underlying C pointer/object. Conversely, `gi::wrap` can be |
| 775 | used to obtain a wrapper from a C pointer/object obtained by some means. |
| 776 | With that in mind, the following are some workarounds; |
| 777 | |
| 778 | * function call; |
| 779 | using/given the above, the C function can then (simply) be called directly |
| 780 | |
| 781 | * custom subclass virtual method; |
| 782 | use `--class-full` to generate a virtual method with plain C signature |
| 783 | |
| 784 | * signal; |
| 785 | use `Object::connect_unchecked` (see also `gst.cpp` example) |
| 786 | |
| 787 | * callback; |
| 788 | use `gi::callback_wrapper` (see also in same example location as above). |
| 789 | Or perhaps there is an API variant using closures which may be useful in |
| 790 | combination with some `Closure::from_*` helpers (see still same example). |
| 791 | |
| 792 | |
| 793 | ## SEE ALSO |
| 794 | g-ir-scanner(1) |