GLib Documentation

repository·main·Indexed 23 days ago

https://github.com/gnome/glib

A low-level core library providing essential foundation services for GNOME and GTK, including C data structure handling, portability wrappers, and runtime interfaces for event loops, threading, dynamic loading, and an object system. Documentation covers API components (GLib, GObject, GModule, GIO), build configuration via Meson, backporting policies, and contributor guidelines for issue triage and merge request management.

Tokens
104.2K
Snippets
125
Records
488
Agent score
83%

What's inside GLib

  1. Overview of the GIO commandline tool

    main

    The gio utility provides a command-line interface for GIO (Gnome Input/Output) features. Unlike traditional utilities that operate only on local files, gio commands can use GIO locations (URIs), such as smb://server/resource/file.txt.

    Important Usage Notes:

    • URIs vs Paths: Plain filenames containing a colon (:) are interpreted as URIs with unknown protocols. To treat such a filename as a local path, prefix it with ./ or use the file: protocol.
    • Mount Visibility: gio focuses on mounts relevant to the user (like removable drives). It does not show all system mounts, so its output differs from tools like fdisk.
  2. Use Windows-specific Utilities for Unix emulation

    main

    GLib provides a set of utilities in the GLibWin32 namespace to provide a level of Unix emulation on the Windows platform. These functions help bridge the gap between Windows-specific behaviors and expected Unix-like environments for applications.

    Note: If your application requires full POSIX API compliance, it is recommended to use the Cygwin project instead of relying on GLib's emulation.

  3. Spawning processes in GLib

    main

    GLib provides a g_spawn_…() family of functions for spawning processes, offering a more convenient interface than standard UNIX fork() and exec().

    Depending on your needs, you can use:

    • Synchronous variants: g_spawn_sync (blocks until the process finishes).
    • Asynchronous variants: g_spawn_async and g_spawn_async_with_pipes (non-blocking).
    • Shell-like command line variants: g_spawn_command_line_sync and g_spawn_command_line_async (accepts a single string command line instead of an argument array).

    For a higher-level API that includes stream interfaces for communicating with child processes, use GSubprocess in GIO.

  4. Use glib-mkenums to generate enum descriptions

    main

    glib-mkenums is a utility that parses C code to extract enum definitions and produces descriptions based on user-specified text templates. It is primarily used to generate enumeration types for the GType system, GObject properties, signal marshalling, or GSettings schemas.

    Basic Usage:

    glib-mkenums [OPTION...] [FILE...]

    Key Features:

    • Parses valid C code files.
    • Substitutes keywords in templates to produce customized output.
    • Supports both standard enum and bit-shift flags definitions.
    • Can output to stdout or a specific file using --output <FILE>.
    • Supports reading arguments from a file using @RSPFILE (useful for Windows systems with command-line length limits).
  5. Unicode support in GLib

    main

    GLib provides a comprehensive suite of APIs for handling Unicode characters and strings. It is designed to work primarily with UTF-8, but also supports conversions to and from UTF-16 and UCS-4.

    Key capabilities include:

    • Character Classification: UTF-8 analogues to traditional ctype.h functions.
    • Case Conversion: Functions for case conversion on UTF-8 strings.
    • String Utilities: UTF-8 versions of standard string utility functions.
    • Normalization and Collation: APIs to perform Unicode normalization and collation.
    • Encoding Conversion: Functions to convert between UTF-8, UTF-16, and UCS-4 encodings.
  6. Use glib-genmarshal to generate C code marshallers

    main

    glib-genmarshal is a utility that generates C code marshallers for callback functions used in the GClosure mechanism of GObject. Marshallers are responsible for calling the actual C callback function with the correct parameters on the stack and collecting the return value.

    Marshaller List Format

    The utility reads a list of marshaller specifications from files or standard input (-). Each line represents a marshaller and follows the format:

    RTYPE:PTYPE,PTYPE,...

    • RTYPE is the callback's return type.
    • PTYPE instances are the parameter types.
    • Note: The first and last arguments of the callback are always assumed to be pointers (typically gpointer).
  7. Use the GMarkup parser for simple XML subsets

    main

    The GMarkup parser is a small, efficient, and easy-to-use parser designed for a subset of XML. It is ideal for application data files and configuration files where your application is the sole writer.

    Important Constraints:

    • Do not use for interoperability with full-scale XML applications.
    • Do not use for untrusted input.
    • Encoding: Only UTF-8 is supported.
    • Validation: There is no DTD or validation support.
    • Error Handling: GMarkup does not guarantee an error for all invalid XML; it may accept documents that a full XML parser would reject. However, it will reject documents that are not well-formed.
  8. Use the gresource tool to manage compiled resources

    main

    The gresource command-line tool provides an interface to GResource. It allows you to inspect and extract resources that have been compiled into a dedicated resource file or embedded within an ELF file (such as a binary or a shared library).

    When working with ELF files that contain multiple resource sections, use the --section option to target a specific section. You can identify available sections using the sections command.

  9. GLib Build Dependencies

    main

    To compile GLib, you need a compliant C toolchain, meson, and pkg-config.

    Required Libraries and Tools

    • pkg-config: Used for tracking compilation flags.
    • Python 3.5+: Must conform to PEP 394.
    • iconv: Required if your system lacks the iconv() function. If you use GNU libiconv, ensure it is in the default search path (e.g., /usr/local/).
    • gettext (libintl): Required if your system lacks gettext() functionality.
    • Thread implementation: POSIX threads or win32 threads.
    • PCRE: Used by GRegex. A fallback subproject is used if the system version is unavailable (e.g., on Android).

    Optional Feature Dependencies

    • GIO Extended Attributes: Requires getxattr() (provided by glibc or libattr). Disable with -Dxattr=false.
    • GIO SELinux support: Requires libselinux. Disable with -Dselinux=disabled.
    • DTrace support: Requires sys/sdt.h (provided by SystemTap on Linux). Disable with -Ddtrace=false.
    • SystemTap support: Requires DTrace support. Disable with -Dsystemtap=false.
    • gobject-introspection: Required for generating introspection data and documentation.

    Breaking the dependency cycle with gobject-introspection:

    1. Build GLib with -Dintrospection=disabled.
    2. Build gobject-introspection against that GLib copy.
    3. Re-build GLib with -Dintrospection=enabled (and -Ddocumentation=true if you want to build the API docs).
  10. Use GOption for command-line option parsing

    main

    The GOption command-line parser is a replacement for the popt library. It supports short options (single dash, can be grouped), long options (double dash), and options with arguments (numbers, strings, or filenames).

    Key features include:

    • Argument Handling: Long options can use an equals sign (e.g., --max-size=20) to pass arguments, which is useful if the argument starts with a dash.
    • Rest Arguments: Non-option arguments are returned as 'rest arguments'.
    • Parsing Termination: A -- argument stops further parsing; all subsequent arguments are treated as rest arguments.
    • Automatic Help Generation: Unless disabled via GLib.OptionContext.set_help_enabled, GOption automatically handles --help, -?, --help-all, and --help-groupname to print formatted help text to stdout.
    • Option Grouping: Options can be organized into GLib.OptionGroups, allowing applications to easily incorporate option sets from various libraries into a single GLib.OptionContext.
  11. What is the GLib Object System (GObject)?

    main

    The GLib Object System (GObject) provides an object-oriented framework for C. It is designed to be flexible, extensible, and specifically optimized for cross-language interoperability (e.g., allowing Python or Perl to call C APIs transparently).

    Key components include:

    • A generic type system (GType): Manages registration of single-inherited flat and deep derived types, as well as interfaces. It handles creation, initialization, memory management, and parent/child relationships. It also supports dynamic implementations that can be relocated or unloaded at runtime.
    • Fundamental type implementations: Includes core types like integers, doubles, enums, and structured types.
    • GObject fundamental type: A sample implementation used as a base for object hierarchies.
    • Signal system: A mechanism for user customization of virtual/overridable methods and for object notifications.
    • Parameter/value system: An extensible system for generically handling object properties and parameterized types.
  12. Use fixed-width integer types in GLib

    main

    GLib provides a set of fixed-width integer types to ensure consistent bit-widths across different platforms.

    Best Practice: In new code, you should prefer standard C99 types (like int8_t, uint32_t, etc.) over GLib-specific types (like gint8, guint32), unless you need to maintain consistency with existing GLib APIs.

    Available Types

    TypeBitsSignedRange (approx)
    gint88Yes-128 to 127
    guint88No0 to 255
    gint1616Yes-32,768 to 32,767
    guint1616No0 to 65,535
    gint3232Yes-2.1B to 2.1B
    guint3232No0 to 4.2B
    gint6464Yes-9.2e18 to 9.2e18
    guint6464No0 to 1.8e19