The .hg and .ccg files
| Appendix G. Wrapping C Libraries with gmmproc |

## The .hg and .ccg files

The .hg and .ccg source files are very much like .h anc .cc C++ source files, but they contain extra macros, such as `_CLASS_GOBJECT()` and `_WRAP_METHOD()`, from which gmmproc generates appropriate C++ source code, usually at the same position in the header. Any additional C++ source code will be copied verbatim into the corresponding .h or .cc file.

A .hg file will typically include some headers and then declare a class, using some macros to add API or behaviour to this class. For instance, gtkmm's `button.hg` looks roughly like this:

    #include <gtkmm/bin.h>
    #include <gtkmm/stockid.h>
    _DEFS(gtkmm,gtk)
    _PINCLUDE(gtkmm/private/bin_p.h)

    namespace Gtk
    {

    class Button : public Bin
    {
      _CLASS_GTKOBJECT(Button,GtkButton,GTK_BUTTON,Gtk::Bin,GtkBin)
    public:

      _CTOR_DEFAULT
      explicit Button(const Glib::ustring& label, bool mnemonic = false);
      explicit Button(const StockID& stock_id);

      _WRAP_METHOD(void set_label(const Glib::ustring& label), gtk_button_set_label)

      ...

      _WRAP_SIGNAL(void clicked(), "clicked")

      ...

      _WRAP_PROPERTY("label", Glib::ustring)
    };

    } // namespace Gtk

The macros in this example do the following:

`_DEFS()`

  Specifies the destination directry for generated sources, and the name of the main .defs file that gmmproc should parse.

`_PINCLUDE()`

  Tells gmmproc to include a header from the generated private/button_p.h file.

`_CLASS_GTKOBJECT()`

  Tells gmmproc to add some typedefs, constructors, and standard methods to this class, as appropriate when wrapping a GtkObject-derived type.

`_WRAP_METHOD()`, `_WRAP_SIGNAL()`, and `_WRAP_PROPERTY()`

  Add methods to wrap parts of the C API.

The .h and .cc files will be generated from the .hg and .ccg files by processing them with gmmproc like so, though this happens automatically when using the above build structure:

    $ cd gtk/src
    $ /usr/lib/glibmm-2.4/proc/gmmproc -I ../../tools/m4 --defs . button . ./../gtkmm

Notice that we provided gmmproc with the path to the .m4 convert files, the path to the .defs file, the name of a .hg file, the source directory, and the destination directory.

You should avoid including the C header from your C++ header, to avoid polluting the global namespace, and to avoid exporting unnecessary public API. But you will need to include the necessary C headers from your .ccg file.

The macros are explained in more detail in the following sections.

### m4 Conversions

The macros that you use in the .hg and .ccg files often need to know how to convert a C++ type to a C type, or vice-versa. gmmproc takes this information from an .m4 file in your `tools/m4/` directory. This allows it to call a C function in the implementation of your C++ method, passing the appropriate parameters to that C functon. For instance, this tells gmmproc how to convert a GtkTreeView pointer to a Gtk::TreeView pointer:

    _CONVERSION(`GtkTreeView*',`TreeView*',`Glib::wrap($3)')

`$3` will be replaced by the parameter name when this conversion is used by gmmproc.

Some extra macros make this easier and consistent. Look in gtkmm's .m4 files for examples. For instance:

    _CONVERSION(`PrintSettings&',`GtkPrintSettings*',__FR2P)
    _CONVERSION(`const PrintSettings&',`GtkPrintSettings*',__FCR2P)
    _CONVERSION(`const Glib::RefPtr<Printer>&',`GtkPrinter*',__CONVERT_REFPTR_TO_P($3))

### Class macros

The class macro declares the class itself and its relationship with the underlying C type. It generates some internal constructors, the member `gobject_`, typedefs, the `gobj()` accessors, type registration, and the `Glib::wrap()` method, among other things.

Other macros, such as `_WRAP_METHOD()` and `_SIGNAL()` may only be used after a call to a `_CLASS_*` macro.

#### _CLASS_GOBJECT

This macro declares a wrapper for a type that is derived from `GObject`, but which is not derived from `GtkObject`.

`_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )`

For instance, from `accelgroup.hg`:

    _CLASS_GOBJECT(AccelGroup, GtkAccelGroup, GTK_ACCEL_GROUP, Glib::Object, GObject)

#### _CLASS_GTKOBJECT

This macro declares a wrapper for a type that is derived from `GtkObject`, such as a widget or dialog.

`_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )`

For instance, from `button.hg`:

    _CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Bin, GtkBin)

#### _CLASS_BOXEDTYPE

This macro declares a wrapper for a non-`GObject` struct, registered with `g_boxed_type_register_static()`.

`_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )`

For instance, for `Gdk::Color`:

    _CLASS_BOXEDTYPE(Color, GdkColor, NONE, gdk_color_copy, gdk_color_free)

#### _CLASS_BOXEDTYPE_STATIC

This macro declares a wrapper for a simple assignable struct such as `GdkRectangle`. It is similar to `_CLASS_BOXEDTYPE`, but the C struct is not allocated dynamically.

`_CLASS_BOXEDTYPE_STATIC( C++ class, C class )`

For instance, for `Gdk::Rectangle`:

    _CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)

#### _CLASS_OPAQUE_COPYABLE

This macro declares a wrapper for an opaque struct that has copy and free functions. The new, copy and free functions will be used to instantiate the default constructor, copy constructor and destructor.

`_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )`

For instance, for `Gdk::Region`:

    _CLASS_OPAQUE_COPYABLE(Region, GdkRegion, gdk_region_new, gdk_region_copy, gdk_region_destroy)

#### _CLASS_OPAQUE_REFCOUNTED

This macro declares a wrapper for a reference-counted opaque struct. The C++ wrapper cannot be directly instantiated and can only be used with `Glib::RefPtr`.

`_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, ref function, unref function )`

For instance, for `Pango::Coverage`:

    _CLASS_OPAQUE_REFCOUNTED(Coverage, PangoCoverage, pango_coverage_new, pango_coverage_ref, pango_coverage_unref)

#### _CLASS_GENERIC

This macro can be used to wrap structs which don't fit into any specialized category.

`_CLASS_GENERIC( C++ class, C class )`

For instance, for `Pango::AttrIter`:

    _CLASS_GENERIC(AttrIter, PangoAttrIterator)

#### _CLASS_INTERFACE

This macro declares a wrapper for a type that is derived from `GObject`, but which is not derived from `GtkObject`.

`_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )`

For instance, from `celleditable.hg`:

      _CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)

Two extra parameters are optional, for the case that the interface derives from another interface, which should be the case when the GInterface has another GInterface as a prerequisitite. For instance, from `loadableicon.hg`:

      _CLASS_INTERFACE(LoadableIcon, GLoadableIcon, G_LOADABLE_ICON, GLoadableIconIface, Icon, GIcon)

### Constructor macros

The `_CTOR_DEFAULT()` and `_WRAP_CTOR()` macros add constructors, wrapping the specified `*_new()` C functions. These macros assume that the C object has properties with the same names as the function parameters, as is usually the case, so that it can supply the parameters directly to a `g_object_new()` call. These constructors never actually call the `*_new()` C functions, because gtkmm must actually instantiate derived GTypes, and the `*_new()` C functions are meant only as convenience functions for C programmers.

When using `_CLASS_GOBJECT()`, the constructors should be protected (rather than public) and each constructor should have a corresponding `_WRAP_CREATE()` in the public section. This prevents the class from being instantiated without using a `RefPtr`. For instance:

    class ActionGroup : public Glib::Object
    {
      _CLASS_GOBJECT(ActionGroup, GtkActionGroup, GTK_ACTION_GROUP, Glib::Object, GObject)

    protected:
      _WRAP_CTOR(ActionGroup(const Glib::ustring& name = Glib::ustring()), gtk_action_group_new)

    public:
      _WRAP_CREATE(const Glib::ustring& name = Glib::ustring())

#### _CTOR_DEFAULT

This macro creates a default constructor with no arguments.

#### _WRAP_CTOR

This macro creates a constructor with arguments, equivalent to a `*_new()` C function. It won't actually call the `*_new()` function, but will simply create an equivalent constructor with the same argument types. It takes a C++ constructor signature, and a C function name.

#### Hand-coding constructors

When a constructor must be partly hand written because, for instance, the `*_new()` C function's parameters do not correspond directly to object properties, or because the `*_new()` C function does more than call `g_object_new()`, the `_CONSTRUCT()` macro may be used in the .ccg file to save some work. The `_CONSTRUCT` macro takes a series of property names and values. For instance, from `button.ccg`:

    Button::Button(const Glib::ustring& label, bool mnemonic)
    :
      _CONSTRUCT("label", label.c_str(), "use_underline", gboolean(mnemonic))
    {}

### Method macros

#### _WRAP_METHOD

This macro generates the C++ method to wrap a C function.

`_WRAP_METHOD( C++ method signature, C function name)`

For instance, from `entry.hg`:

    _WRAP_METHOD(void set_text(const Glib::ustring& text), gtk_entry_set_text)

The C function (e.g. `gtk_entry_set_text`) is described more fully in the .defs file, and the `convert*.m4` files contain the necessary conversion from the C++ parameter type to the C parameter type. This macro also generates doxygen documentation comments based on the `*_docs.xml` and `*_docs_override.xml` files.

There are some optional extra arguments:

refreturn

  Do an extra reference() on the return value, in case the C function does not provide a reference.

errthrow

  Use the last GError* parameter of the C function to throw an exception.

deprecated

  Puts the generated code in #ifdef blocks. Text about the deprecation can be specified as an optional parameter.

constversion

  Just call the non-const version of the same function, instead of generating almost duplicate code.

Though it's usually obvious what C++ types should be used in the C++ method, here are some hints:

- Objects used via `RefPtr`: Pass the `RefPtr` as a const reference. For instance, `const Glib::RefPtr<Gtk::Action>& action`.

- Const Objects used via `RefPtr`: If the object should not be changed by the function, then make sure that the object is const, even if the `RefPtr` is already const. For instance, `const Glib::RefPtr<const Gtk::Action>& action`.

- Wrapping `GList*` and `GSList*` parameters: First, you need to discover what objects are contained in the list's data field for each item, usually by reading the documentation for the C function. The list can then be wrapped by an appropriate intermediate type, such as `Glib::ListHandle` or `Glib::SListHandle`. These are templates, so you can specify the item type. For instance, `Glib::ListHandle< Glib::RefPtr<Action> >`. Existing typedefs exist for some common list types. You may need to define a Traits type to specify how the C and C++ types should be converted.

- Wrapping `GList*` and `GSList*` return types: You must discover whether the caller should free the list and whether it should release the items in the list, again by reading the documentation of the C function. With this information you can choose the ownership (none, shallow or deep) for the m4 conversion rule, which you should probably put directly into the .hg file because the ownership depends on the function rather than the type. For instance:

      #m4 _CONVERSION(`GSList*', `Glib::SListHandle<Widget*>', `$2($3, Glib::OWNERSHIP_NONE)')

#### _WRAP_METHOD_DOCS_ONLY

This macro is like `_WRAP_METHOD()`, but it generates only the documentation for a C++ method that wraps a C function. Use this when you must hand-code the method, but you want to use the documentation that would be generated if the method was generated.

`_WRAP_METHOD_DOCS_ONLY(C function name)`

For instance, from `container.hg`:

    _WRAP_METHOD_DOCS_ONLY(gtk_container_remove)

#### _IGNORE()

gmmproc will warn you on stdout about functions that you have forgotten to wrap, helping to ensure that you are wrapping the complete API. Buf if you don't want to wrap some functions or if you chose to hand-code some methods then you can use the _IGNORE() macro the make gmmproc stop complaining.

`_IGNORE(C function name 1, C function name2, etc)`

For instance, from `buttonbox.hg`:

    _IGNORE(gtk_button_box_set_spacing, gtk_button_box_get_spacing,

#### _WRAP_SIGNAL

This macro generates the C++ libsigc++-style signal to wrap a C GObject signal. It actually generates a public accessor method, such as `signal_clicked()`, which returns a proxy object. gmmproc uses the .defs file to discover the C parameter types and the .m4 convert files to discover appropriate type conversions.

`_WRAP_SIGNAL( C++ signal handler signature, C signal name)`

For instance, from `button.hg`:

    _WRAP_SIGNAL(void clicked(),"clicked")

Signals usually have function pointers in the GTK struct, with a corresponding enum value. and a `g_signal_new()` in the .c file.

There are some optional extra arguments:

no_default_handler

  Do not generate an `on_something()` virtual method to allow easy overriding of the default signal handler. Use this when adding a signal with a default signal handler would break the ABI by increasing the size of the class's virtual function table.

#### _WRAP_PROPERTY

This macro generates the C++ method to wrap a C GObject property. You must specify the property name and the wanted C++ type for the property. gmmproc uses the .defs file to discover the C type and the .m4 convert files to discover appropriate type conversions.

`_WRAP_PROPERTY(C property name, C++ type)`

For instance, from `button.hg`:

    _WRAP_PROPERTY("label", Glib::ustring)

### Other macros

#### _WRAP_ENUM

This macro generates a C++ enum to wrap a C enum. You must specify the desired C++ name and the name of the underlying C enum.

For instance, from `widget.hg`:

    _WRAP_ENUM(WindowType, GdkWindowType)

If the enum is not a `GType`, you must pass a third parameter NO_GTYPE. This is the case when there is no `*_get_type()` function for the C enum, but be careful that you don't just need to include an extra header for that function. You should also file a bug against the C API, because all enums should be regeistered as GTypes.

For example:

    _WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags)

#### _WRAP_GERROR

This macro generates a C++ exception class, derived from Glib::Error, with a Code enum and a code() method. You must specify the desired C++ name, the name of the corresponding C enum, and the prefix for the C enum values.

This exception can then be thrown by methods which are generated from _WRAP_METHOD() with the errthrow option.

For instance, from `pixbuf.hg`:

    _WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)

#### _MEMBER_GET / _MEMBER_SET

Use these macro if you're wrapping a simple struct or boxed type that provides direct access to its data members, to create getters and setters for the data members.

`_MEMBER_GET(C++ name, C name, C++ type, C type)`

`_MEMBER_SET(C++ name, C name, C++ type, C type)`

For example, in `rectangle.hg`:

    _MEMBER_GET(x, x, int, int)

#### _MEMBER_GET_PTR / _MEMBER_SET_PTR

Use these macros to automatically provide getters and setters for a data member that is a pointer type. For the getter function, it will create two methods, one const and one non-const.

`_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)`

`_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)`

For example, in `dialog.hg`:

    _MEMBER_GET_PTR(vbox, vbox, VBox*, GtkWidget*)

#### _MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT

Use this macro to provide getters and setters for a data member that is a `GObject` type that must be referenced before being returned.

`_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)`

`_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)`

For example, in `progress.hg`:

    _MEMBER_GET_GOBJECT(offscreen_pixmap, offscreen_pixmap, Gdk::Pixmap, GdkPixmap*)

### Basic Types

Some of the basic types that are used in C APIs have better alternatives in C++. For example, there's no need for a gboolean type since C++ has bool. The following list shows some commonly-used types in C APIs and what you might convert them to in a C++ wrapper library.

Basic Type equivalents

C type | C++ type
--- | ---
gboolean | bool
gint | int
guint | guint
gdouble | double
gunichar | gunichar
gchar* | `Glib::ustring` (or `std::string` for filenames)

Generating the .defs files. |  | Hand-coded source files