A script-enabled browser is required for this page to function properly.

ORA_FFI.Example 2

Here is an alternative way to implement the C function pow, shown in Ora_Ffi Example 1. This example uses the Ora_Ffi.Generate_Foreign function to generate a PL/SQL package. The PRAGMA compiler directive, necessary to compile the foreign C function, is automatically included in the generated package, so it is not used in the package body below.


/* Create package mathlib that will generate a PL/SQL 
package using a foreign file C function to raise a 
number to a power. The parameter, pkg_name, lets you 
specify the name of the generated package. */
PACKAGE mathgen IS
   PROCEDURE gen(pkg_name IN VARCHAR2);
END; 


PACKAGE BODY mathgen IS
   /* Define the 'gen' procedure that will generate the 
      foreign file package. */
   PROCEDURE gen(pkg_name IN VARCHAR2) IS
      /* Declare the library and function handles. */
      mathlib_lhandle   Ora_Ffi.Libhandletype ;
      to_power_fhandle  Ora_Ffi.Funchandletype ;

   BEGIN   /* package body mathlib */
      /* Load the library. */
      mathlib_lhandle := Ora_Ffi.Load_Library 
         ('C:/WINDOWS/SYSTEM/', 'msvcrt.dll');

      /* Register the foreign function. */
      to_power_fhandle := Ora_Ffi.Register_Function
         (mathlib_lhandle, 'pow', Ora_Ffi.C_Std);

      /* Register both parameters of the foreign function. */
      Ora_Ffi.Register_Parameter (to_power_fhandle,
                             Ora_Ffi.C_DOUBLE);
      Ora_Ffi.Register_Parameter(to_power_fhandle,
                             Ora_Ffi.C_DOUBLE);

      /* Register the return type of the foreign function. */
      Ora_Ffi.Register_Return (to_power_fhandle, Ora_Ffi.C_DOUBLE);

      /* Generate a PL/SQL package containing the foreign C function,
         'pow.' You can name the new package by specifying a value
          for the parameter, pkg_name, when you generate the package. */ 
      Ora_Ffi.generate_foreign(mathlib_lhandle, pkg_name);

   END; /* Procedure gen */
END; /* Package Body mathgen */

To raise a number to a power with this method, you must first generate a Pl/SQL package using package mathgen and procedure gen. For example, if the generated PL/SQL power package is called mathlib, you would generate it as follows:


PL/SQL> mathgen.gen('mathlib'); 

Then, to invoke the power function from package mathlib, you might write a procedure such as:


PROCEDURE raise_to_power (a in number, b in number) IS
   BEGIN
      text_io.put_line(mathlib.pow(a,b));
   END;

PL/SQL> raise_to_power(5,2);

25