Advanced > Writing operators [src]

This section runs quickly through adding a simple operator to libvips. For more information, see VipsOperation and VipsRegion. A good starting point for a new operation is a similar one in libvips.

All libvips operations are subclasses of VipsOperation, which in turn subclasses VipsObject and then GObject. You add an operation to libvips by defining a new subclass of VipsOperation and arranging for its class_init() to be called, perhaps by calling its get_type() function.

The class and object structures

First you need to define a new object struct and a new class struct.

typedef struct _Negative {
  VipsOperation parent_instance;

  VipsImage *in;
  VipsImage *out;

  int image_max;

} Negative;

typedef struct _NegativeClass {
  VipsOperationClass parent_class;

  /* No new class members needed for this op.
   */

} NegativeClass;

This operation will find the photographic negative of an unsigned 8-bit image, optionally letting you specify the value which the pixels “pivot” about. It doesn’t need any class members (ie. values common to all operations of this type), so the second struct is empty. See the source to vips_invert() for a more complete version of this operation that’s actually in the library.

GObject has a handy macro to write some of the boilerplate for you.

G_DEFINE_TYPE(Negative, negative, VIPS_TYPE_OPERATION);

G_DEFINE_TYPE() defines a function called negative_get_type(), which registers this new class and returns its GType (a pointer-sized integer). negative_get_type() in turn needs two functions, negative_init(), to initialise a new instance, and negative_class_init(), to initialise a new class.

Class and object initialisation