Home | Previous Page | Next Page   Creating User-Defined Routines > Creating Special-Purpose UDRs >

Writing a Cast Function

A cast function is a user-defined function that converts one data type (the source data type), to another data type (the target data type). A cast can be one of the following types:

Tip:
This section describes how to create a cast function that is written in C. For general information on how to create user-defined functions and casts, see the IBM Informix: User-Defined Routines and Data Types Developer's Guide.
To register a C UDR as a cast function
  1. Use the CREATE FUNCTION statement to register the C function as a C UDR.

    For more information, see Registering a C UDR.

  2. Use the CREATE CAST statement to register the cast in the database.

    Casts are stored in the syscasts system catalog table. For more information on the syntax of the CREATE CAST statement, see the IBM Informix: Guide to SQL Syntax

The following lines register the C function, a_to_b( ), as an implicit cast from the a to b data type:

CREATE FUNCTION a_to_b(source a)
RETURNS b
EXTERNAL NAME '/usr/udrs/casts.so(a_to_b)'
LANGUAGE C;

CREATE CAST (a AS b WITH a_to_b);

These SQL statements assume that a and b are already registered as user-defined types. These statements only provide the ability to convert from type a to type b. To provide the ability to cast from the b to the a data type, you must create a second cast, as the following sample lines show:

CREATE FUNCTION b_to_a(source b)
RETURNS a
EXTERNAL NAME '/usr/udrs/casts.so(b_to_a)'
LANGUAGE C;

CREATE CAST (b AS a WITH b_to_a);

The following lines declare the C function, a_to_b( ), which accepts the a fixed-length opaque type as an argument and returns the b fixed-length opaque type:

b_t *a_to_b(source_type)
   a_t *source_type;
{
   b_t *target;

   target = (b_t *)mi_alloc(sizeof(b_t));

   /* Perform necessary conversions from a to b */

   return ( target );
}
Home | [ Top of Page | Previous Page | Next Page | Contents | Index ]