Los archivos .hg y .ccg

Los archivos de fuentes .hg y .ccg se parecen mucho a los archivos de fuentes .h y .cc de C++, pero contienen macros adicionales, como _CLASS_GOBJECT() y _WRAP_METHOD(), desde las que gmmproc genera código fuente de C++ apropiado, generalmente en la misma posición en la cabecera. Cualquier código fuente adicional de C++ se copiará tal cual en el archivo .h o .cc correspondiente.

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/activatable.h>
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/bin_p.h)

namespace Gtk
{

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

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

  _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 directory for generated sources, and the name of the main .defs file that gmmproc should parse.

_PINCLUDE()

Tells gmmproc to include a header in 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 widget.

_IMPLEMENTS_INTERFACE()

Tells gmmproc to add initialization code for the interface.

_CTOR_DEFAULT

Add a default constructor.

_WRAP_METHOD(), _WRAP_SIGNAL(), _WRAP_PROPERTY(), and _WRAP_CHILD_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

Tenga en cuenta que se le proporcionó a gmmproc la ruta de los archivos de conversión .m4, la ruta del archivo .defs, el nombre de un archivo .hg, la carpeta de las fuentes, y la carpeta de destino.

Debe evitar incluir la cabecera de C desde su cabecera de C++, para evitar contaminar el espacio de nombres global, y para evitar exportar API pública innecesaria. Pero necesitará incluir las cabeceras de C desde su archivo .ccg.

Las macros se explican en mayor detalle en las secciones siguientes.

G.3.1. Conversiones m4

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 se reemplazará por el nombre del parámetro cuando gmmproc use esta conversión.

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))

G.3.2. Inicializaciones de m4

Cuando se envuelven métodos, a menudo es deseable almacenar el valor que devuelve una función de C en lo que se conoce como parámetro de salida. En este caso, el método de C++ devuelve void pero se incluye en su lista de argumentos un parámetro de salida en el que se almacena el valor de la función de C. gmmproc permite esta funcionalidad, pero deben incluirse macros de inicialización apropiadas para decirle a gmmproc cómo inicializar el parámetro de C++ desde el valor de devolución de la función de C.

For example, if there was a C function that returned a GtkWidget* and for some reason, instead of having the C++ method also return the widget, it was desirable to have the C++ method place the widget in a specified output parameter, an initialization macro such as the following would be necessary:

_INITIALIZATION(`Gtk::Widget&',`GtkWidget*',`$3 = Glib::wrap($4)')

$3 se reemplazará por el nombre del parámetro de salida del método de C++ y $4 se reemplazará por el valor de retorno de la función de C cuando gmmproc use esta inicialización. Por conveniencia, $1 también se reemplazará por el tipo de C++ sin el «et» (&) y $2 se reemplazará por el tipo de C.

G.3.3. Macros de clases

Las macros de clases declaran la clase en sí y su relación con el tipo de C subyacente. Generan algunos constructores internos, el miembro gobject_, «typedefs», los gobj() de acceso, registro de tipos, y el método Glib::wrap(), entre otras cosas.

Otras macros, como _WRAP_METHOD() y _WRAP_SIGNAL() sólo pueden usarse después de una llamada a una macro _CLASS_*.

G.3.3.1. _CLASS_GOBJECT

Esta macro declara un envoltorio de un tipo que deriva de GObject, pero cuyo envoltorio no deriva de Gtk::Object.

_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)

G.3.3.2. _CLASS_GTKOBJECT

Esta macro declara un envoltorio para un tipo cuyo envoltorio deriva de Gtk::Object, como un widget o un diálogo.

_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)

Típicamente usará esta macro cuando la clase ya derive de Gtk::Object. Por ejemplo, la usará cuando envuelva un widget de GTK+, porque Gtk::Widget deriva de Gtk::Object.

También podrá derivar clases que no sean widgets de Gtk::Object para que puedan usarse sin Glib::RefPtr. Por ejemplo, podrían instanciarse con Gtk::manage() o en la pila como una variable miembro. Esto es cómodo, pero sólo debe usarlo cuando esté seguro de que no se necesita conteo de referencias real. Se considera de utilidad para los widgets.

G.3.3.3. _CLASS_BOXEDTYPE

Esta macro declara un envoltorio para una estructura que no es GObject, registrada con g_boxed_type_register_static().

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

For instance, from Gdk::RGBA:

_CLASS_BOXEDTYPE(RGBA, GdkRGBA, NONE, gdk_rgba_copy, gdk_rgba_free)

G.3.3.4. _CLASS_BOXEDTYPE_STATIC

Esta macro declara un envoltorio para una estructura asignable simple como GdkRectangle. Es similar a _CLASS_BOXEDTYPE, pero la estructura de C no se asigna dinámicamente.

_CLASS_BOXEDTYPE_STATIC( C++ class, C class )

For instance, for Gdk::Rectangle:

_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)

G.3.3.5. _CLASS_OPAQUE_COPYABLE

Esta macro declara un envoltorio para una estructura opaca que tiene funciones «copy» y «free». Las funciones «new», «copy» y «free» se usarán para instanciar el constructor predeterminado, copiar el constructor y el destructor.

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

For instance, from Glib::Checksum:

_CLASS_OPAQUE_COPYABLE(Checksum, GChecksum, NONE, g_checksum_copy, g_checksum_free)

G.3.3.6. _CLASS_OPAQUE_REFCOUNTED

Esta macro declara un envoltorio para una estructura opaca con conteo de referencias. El envoltorio de C++ no puede instanciarse directamente y sólo lo puede usar Glib::RefPtr.

_CLASS_OPAQUE_REFCOUNTED( 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)

G.3.3.7. _CLASS_GENERIC

Esta macro puede usarse para envolver estructuras que no se ajustan a ninguna categoría especializada.

_CLASS_GENERIC( C++ class, C class )

For instance, for Pango::AttrIter:

_CLASS_GENERIC(AttrIter, PangoAttrIterator)

G.3.3.8. _CLASS_INTERFACE

Esta macro declara un envoltorio para un tipo que deriva de GTypeInterface.

_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 prerequisite. For instance, from loadableicon.hg:

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

G.3.4. Macros de constructores

Las macros _CTOR_DEFAULT() y _WRAP_CTOR() añaden constructores, envolviendo las funciones de C *_new() especificadas. Estas macros asumen que el objeto de C tiene propiedades con los mismos nombres que los parámetros de función, como es usual, para que pueda proporcionar los parámetros directamente a una llamada de g_object_new(). Estos constructores nunca llaman realmente a funciones de C *_new(), porque gtkmm debe en realidad instanciar «GTypes» derivados, y las funciones *_new() de C sólo están pensadas como funciones cómodas para programadores de C.

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 TextMark : public Glib::Object
{
  _CLASS_GOBJECT(TextMark, GtkTextMark, GTK_TEXT_MARK, Glib::Object, GObject)

protected:
  _WRAP_CTOR(TextMark(const Glib::ustring& name, bool left_gravity = true), gtk_text_mark_new)

public:
  _WRAP_CREATE(const Glib::ustring& name, bool left_gravity = true)

G.3.4.1. _CTOR_DEFAULT

Esta macro crea un constructor predeterminado sin argumentos.

G.3.4.2. _WRAP_CTOR

Esta macro crea un constructor con argumentos, equivalente a una función de C *_new(). En realidad no llamará a la función *_new(), sino que simplemente creará un constructor equivalente con los mismos tipos de argumentos. Toma una firma de constructor de C++ y un nombre de función de C.

It also takes an optional extra argument:

errthrow

This tells gmmproc that the C *_new() has a final GError** parameter which should be ignored.

G.3.4.3. Escribir constructores a mano

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))
{}

G.3.5. Macros de métodos

G.3.5.1. _WRAP_METHOD

Esta macro genera el método de C++ para envolver una función de C.

_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)

La función de C (por ejemplo, gtk_entry_set_text) se describe en mayor detalle en el archivo .defs, y los archivos convert*.m4 contienen la conversión necesaria del tipo de parámetro de C++ al tipo de C. Esta macro también genera comentarios de documentación de Doxygen basados en los archivos *_docs.xml y *_docs_override.xml.

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 ["<text>"]

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.

newin "<version>"

Adds a @newin Doxygen command to the documentation, or replaces the @newin command generated from the C documentation.

ifdef <identifier>

Puts the generated code in #ifdef blocks.

slot_name <parameter_name>

Specifies the name of the slot parameter of the method, if it has one. This enables gmmproc to generate code to copy the slot and pass the copy on to the C function in its final gpointer user_data parameter. The slot_callback option must also be used to specify the name of the glue callback function to also pass on to the C function.

slot_callback <function_name>

Used in conjunction with the slot_name option to specify the name of the glue callback function that handles extracting the slot and then calling it. The address of this callback is also passed on to the C function that the method wraps.

no_slot_copy

Tells gmmproc not to pass a copy of the slot to the C function, if the method has one. Instead the slot itself is passed. The slot parameter name and the glue callback function must have been specified with the slot_name and slot_callbback options respectively.

Selecting which C++ types should be used is also important when wrapping C API. 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::FileFilter>& filter.
  • 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::FileFilter>& filter.
  • 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 a std::vector type. For instance, std::vector< Glib::RefPtr<Gdk::Pixbuf> >. 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*',`std::vector<Widget*>',`Glib::SListHandler<Widget*>::slist_to_vector($3, Glib::OWNERSHIP_SHALLOW)')

G.3.5.2. _WRAP_METHOD_DOCS_ONLY

Esta macro es similar a _WRAP_METHOD(), pero sólo genera la documentación de un método de C++ que envuelve una función de C. Úsela cuando debe escribir el método a mano, pero quiere usar la documentación que se crearía si el método se generara.

_WRAP_METHOD_DOCS_ONLY(C function name)

For instance, from container.hg:

_WRAP_METHOD_DOCS_ONLY(gtk_container_remove)

There are some optional extra arguments:

errthrow

Excludes documentation of the last GError** parameter of the C function.

newin "<version>"

Adds a @newin Doxygen command to the documentation, or replaces the @newin command generated from the C documentation.

G.3.5.3. _IGNORE, _IGNORE_SIGNAL, _IGNORE_PROPERTY, _IGNORE_CHILD_PROPERTY

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

_IGNORE(C function name 1, C function name 2, etc) _IGNORE_SIGNAL(C signal name 1, C signal name 2, etc) _IGNORE_PROPERTY(C property name 1, C property name 2, etc) _IGNORE_CHILD_PROPERTY(C child property name 1, C child property name 2, etc)

For instance, from flowbox.hg:

_IGNORE(gtk_flow_box_set_filter_func, gtk_flow_box_set_sort_func)
_IGNORE_SIGNAL(activate-cursor-child, toggle-cursor-child, move-cursor)

G.3.5.4. _WRAP_SIGNAL

Esta macro genera la señal de C++ con el estilo de libsigc++ para envolver una señal GObject de C. En realidad genera un método de acceso público, como signal_clicked(), que devuelve un objeto sustituto. gmmproc usa el archivo .defs para descubrir los tipos de parámetro de C y los archivos de conversión .m4 para descubrir conversiones de tipo adecuadas.

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

For instance, from button.hg:

_WRAP_SIGNAL(void clicked(),"clicked")

Las señales generalmente tienen punteros de funciones en la estructura de GTK, con un valor de enum correspondiente y un g_signal_new() en el archivo .c.

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.

custom_default_handler

Generate a declaration of the on_something() virtual method in the .h file, but do not generate a definition in the .cc file. Use this when you must generate the definition by hand.

custom_c_callback

Do not generate a C callback function for the signal. Use this when you must generate the callback function by hand.

refreturn

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

deprecated ["<text>"]

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

newin "<version>"

Adds a @newin Doxygen command to the documentation, or replaces the @newin command generated from the C documentation.

ifdef <identifier>

Puts the generated code in #ifdef blocks.

exception_handler <method_name>

Allows to use custom exception handler instead of default one. Exception might be rethrown by user-defined handler, and it will be caught by default handler.

detail_name <parameter_name>

Adds a const Glib::ustring& parameter to the signal_something() method. Use it, if the signal accepts a detailed signal name, i.e. if the underlying C code registers the signal with the G_SIGNAL_DETAILED flag.

two_signal_methods

Used in conjunction with the detail_name option to generate two signal_something() methods, one without a parameter and one with a parameter without a default value. With only the detail_name option one method is generated, with a parameter with default value. Use the two_signal_methods option, if it's necessary in order to preserve ABI.

G.3.5.5. _WRAP_PROPERTY

Esta macro genera el método de C++ que envuelve una propiedad GObject de C. Debe especificar el nombre de la propiedad y el tipo de C++ que quiere para la propiedad. gmmproc usa el archivo .defs para descubrir el tipo de C y el archivo de conversión .m4 para descubrir conversiones de tipo apropiadas.

_WRAP_PROPERTY(C property name, C++ type)

For instance, from button.hg:

_WRAP_PROPERTY("label", Glib::ustring)

There are some optional extra arguments:

deprecated ["<text>"]

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

newin "<version>"

Adds a @newin Doxygen command to the documentation, or replaces the @newin command generated from the C documentation.

G.3.5.6. _WRAP_VFUNC

Esta macro genera el método de C++ que envuelve una función virtual de C.

_WRAP_VFUNC( C++ method signature, C function name)

For instance, from widget.hg:

_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)

The C function (e.g. get_request_mode) is described more fully in the *_vfuncs.defs file, and the convert*.m4 files contain the necessary conversion from the C++ parameter type to the C parameter type. Conversions can also be written in the .hg file. Virtual functions often require special conversions that are best kept local to the .hg file where they are used.

There are some optional extra arguments:

refreturn

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

refreturn_ctype

Do an extra reference() on the return value of an overridden something_vfunc() function in the C callback function, in case the calling C function expects it to provide a reference.

keep_return

Keep a copy of the return value in the C callback function, in case the calling C function does not expect to get its own reference.

errthrow

Use the last GError** parameter of the C virtual function (if there is one) to throw an exception.

custom_vfunc

Do not generate a definition of the vfunc in the .cc file. Use this when you must generate the vfunc by hand.

custom_vfunc_callback

Do not generate a C callback function for the vfunc. Use this when you must generate the callback function by hand.

ifdef <identifier>

Puts the generated code in #ifdef blocks.

slot_name <parameter_name>

Specifies the name of the slot parameter of the method, if it has one. This enables gmmproc to generate code to copy the slot and pass the copy on to the C function in its final gpointer user_data parameter. The slot_callback option must also be used to specify the name of the glue callback function to also pass on to the C function.

slot_callback <function_name>

Used in conjunction with the slot_name option to specify the name of the glue callback function that handles extracting the slot and then calling it. The address of this callback is also passed on to the C function that the method wraps.

no_slot_copy

Tells gmmproc not to pass a copy of the slot to the C function, if the method has one. Instead the slot itself is passed. The slot parameter name and the glue callback function must have been specified with the slot_name and slot_callbback options respectively.

return_value <value>

Defines non-default return value.

exception_handler <method_name>

Allows to use custom exception handler instead of default one. Exception might be rethrown by user-defined handler, and it will be caught by default handler.

Una regla para la cual puede haber excepciones: si la función virtual de C devuelve un puntero a un objeto derivado de GObject, es decir un objeto cuyas referencias se cuentan, entonces la función virtual de C++ deberá devolver un objeto Glib::RefPtr<>. Se requiere uno de los argumentos adicionales refreturn o refreturn_ctype.

G.3.5.7. _WRAP_CHILD_PROPERTY

This macro generates the C++ method to wrap a GtkContainer child property. (See GtkContainer for more information about child properties). Similarly to _WRAP_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_CHILD_PROPERTY(C child property name, C++ type)

For instance, from notebook.hg:

_WRAP_CHILD_PROPERTY("tab-expand", bool)

_WRAP_CHILD_PROPERTY() accepts the same optional arguments as _WRAP_PROPERTY().

G.3.6. Otras macros

G.3.6.1. _IMPLEMENTS_INTERFACE

Esta macro genera código de inicialización para la interfaz.

_IMPLEMENTS_INTERFACE(C++ interface name)

For instance, from button.hg:

_IMPLEMENTS_INTERFACE(Activatable)

There is one optional extra argument:

ifdef <identifier>

Puts the generated code in #ifdef blocks.

G.3.6.2. _WRAP_ENUM

Esta macro genera una enum de C++ para envolver una enum de C. Debe especificar el nombre de C++ que quiere y el nombre de la enum de C subyacente.

For instance, from enums.hg:

_WRAP_ENUM(WindowType, GtkWindowType)

Si la enum no es un GType, debe pasar un tercer parámetro «NO_GTYPE». Este es el caso cuando no hay una función *_get_type() para la enum de C, pero tenga cuidado: no sólo necesita incluir una cabecera adicional para esa función, también debe enviar un informe de error de la API de C porque todas las enums deben registrarse como GTypes.

_WRAP_ENUM() accepts the optional newin parameter. See _WRAP_METHOD().

For example, from icontheme.hg:

_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)

G.3.6.3. _WRAP_ENUM_DOCS_ONLY

This macro just generates a Doxygen documentationn block for the enum. This is useful for enums that can't be wrapped with _WRAP_ENUM() because they are complexly defined (maybe using C macros) but including the generated enum documentation is still desired. It is used with the same syntax as _WRAP_ENUM() and also process the same options (though NO_GTYPE is just ignored because it makes no difference when just generating the enum's documentation).

G.3.6.4. _WRAP_GERROR

Esta macro genera una clase de excepción de C++, derivada de Glib::Error, con una enum Code y un método code(). Debe especificar el nombre de C++ que quiere, el nombre de la enum de C correspondiente, y el prefijo de los valores de la enum de C.

Los métodos generados desde _WRAP_METHOD() podrán entonces lanzar esta excepción con la opción «errthrow».

_WRAP_GERROR() accepts the optional newin parameter. See _WRAP_METHOD().

For instance, from pixbuf.hg:

_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)

G.3.6.5. _MEMBER_GET / _MEMBER_SET

Use estas macros si está envolviendo una estructura simple o un tipo en caja que proporciona acceso directo a sus miembros de datos, para crear métodos de acceso y modificación para estos.

_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)

G.3.6.6. _MEMBER_GET_PTR / _MEMBER_SET_PTR

Use estas macros para proporcionar métodos de acceso y modificación para un miembro de datos que es de tipo puntero automáticamente. Para la función de acceso, creará dos métodos, uno constante y otro no constante.

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

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

For example, for Pango::Analysis in item.hg:

// _MEMBER_GET_PTR(engine_lang, lang_engine, EngineLang*, PangoEngineLang*)
// It's just a comment. It's difficult to find a real-world example.

G.3.6.7. _MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT

Use estas macros para proporcionar métodos de acceso y modificación para un miembro de datos que es de tipo GObject que debe referenciarse antes de devolverse.

_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 Pangomm, layoutline.hg:

_MEMBER_GET_GOBJECT(layout, layout, Pango::Layout, PangoLayout*)

G.3.7. Procesado de parámetros de gmmproc

gmmproc allows processing the parameters in a method signature for the macros that process method signatures (like _WRAP_METHOD(), _WRAP_CTOR() and _WRAP_CREATE()) in a variety of ways:

G.3.7.1. Reordenación de parámetros

For all the macros that process method signatures, it is possible to specify a different order for the C++ parameters than the existing order in the C function, virtual function or signal. For example, say that the following C function were being wrapped as a C++ method for the Gtk::Widget class:

        void gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
        GdkEventMask events);
      
However, changing the order of the C++ method's two parameters is necessary. Something like the following would wrap the function as a C++ method with a different order for the two parameters:
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{events},
        const Glib::RefPtr<const Gdk::Device>& device{device}),
        gtk_widget_set_device_events)
      
The {c_param_name} following the method parameter names tells gmmproc to map the C++ parameter to the specified C parameter within the {}. Since the C++ parameter names correspond to the C ones, the above could be re-written as:
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{.}, const
        Glib::RefPtr<const Gdk::Device>& device{.}),
        gtk_widget_set_device_events)
      

Please note that when reordering parameters for a _WRAP_SIGNAL() method signature, the C parameter names would always be p0, p1, etc. because the generate_extra_defs utility uses those parameter names no matter what the C API's parameter names may be. It's how the utility is written presently.

G.3.7.2. Procesado de parámetros opcionales

For all macros processing method signatures except _WRAP_SIGNAL() and _WRAP_VFUNC() it is also possible to make the parameters optional so that extra C++ methods are generated without the specified optional parameter. For example, say that the following *_new() function were being wrapped as a constructor in the Gtk::ToolButton class:

        GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar*
        label);
      
Also, say that the C API allowed NULL for the function's label parameter so that that parameter is optional. It would be possible to have gmmproc generate the original constructor (with all the parameters) along with an additional constructor without that optional parameter by appending a {?} to the parameter name like so:
        _WRAP_CTOR(ToolButton(Widget& icon_widget, const Glib::ustring&
        label{?}), gtk_tool_button_new)
      
In this case, two constructors would be generated: One with the optional parameter and one without it.

G.3.7.3. Procesado de parámetros de salida

With _WRAP_METHOD() it is also possible for the return of the wrapped C function (if it has one) to be placed in an output parameter of the C++ method instead of having the C++ method also return a value like the C function does. To do that, simply include the output parameter in the C++ method parameter list appending a {OUT} to the output parameter name. For example, if gtk_widget_get_request_mode() is declared as the following:

        GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);
      
And having the C++ method set an output parameter is desired instead of returning a SizeRequestMode, something like the following could be used:
        _WRAP_METHOD(void get_request_mode(SizeRequestMode& mode{OUT})
        const, gtk_widget_get_request_mode)
      
The {OUT} appended to the name of the mode output parameter tells gmmproc to place the return of the C function in that output parameter. In this case, however, a necessary initialization macro like the following would also have to be specified:
        _INITIALIZATION(`SizeRequestMode&',`GtkSizeRequestMode',`$3 =
        (SizeRequestMode)($4)')
      
Which could also be written as:
        _INITIALIZATION(`SizeRequestMode&',`GtkSizeRequestMode',`$3 =
        ($1)($4)')
      

_WRAP_METHOD() also supports setting C++ output parameters from C output parameters if the C function being wrapped has any. Suppose, for example, that we want to wrap the following C function that returns a value in its C output parameter rect:

        gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
        GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);
      
To have gmmproc place the value returned in the C++ rect output parameter, something like the following _WRAP_METHOD() directive could be used:
        _WRAP_METHOD(bool get_cell_rect(const TreeModel::Path& path, const
        CellRenderer& cell, Gdk::Rectangle& rect{>>}) const,
        gtk_icon_view_get_cell_rect)
      
The {>>} following the rect parameter name indicates that the C++ output parameter should be set from the value returned in the C parameter from the C function. gmmproc will generate a declaration of a temporary variable in which to store the value of the C output parameter and a statement that sets the C++ output parameter from the temporary variable. In this case it may be necessary to have an _INITIALIZATION() describing how to set a Gdk::Rectangle& from a GdkRectangle* such as the following:
        _INITIALIZATION(`Gdk::Rectangle&',`GdkRectangle', `$3 =
        Glib::wrap(&($4))')
      

G.3.8. Tipos básicos

Algunos de los tipos básicos que se usan en las API de C tienen alternativas mejores en C++. Por ejemplo, no hay necesidad de un tipo gboolean dado que C++ tiene el bool. La siguiente lista muestra algunos tipos comúnmente usados en API de C y en qué los puede convertir en una biblioteca envoltorio de C++

Tipos básicos equivalentes

Tipo de C: gboolean

Tipo de C++: bool

Tipo de C: gint

Tipo de C++: int

Tipo de C: guint

Tipo de C++: guint

Tipo de C: gdouble

Tipo de C++: double

Tipo de C: gunichar

Tipo de C++: gunichar

Tipo de C: gchar*

Tipo de C++: Glib::ustring (or std::string for filenames)