On Sun, 10 Jun 2001, Brian Ingerson wrote:

> Sure. I always want more examples.

Here you are.  Feel free to munge it any way you see fit:

--- C-Cookbook.pod      Wed Jun  6 03:35:50 2001
+++ C-Cookbook.pod.new  Sun Jun 10 16:23:56 2001
@@ -214,6 +214,90 @@

 =cut --------------------------------------------------------------------------

+=head2 Named Parameters
+
+=over 4
+
+=item Problem
+
+How do I wrap a C function with a named-parameter interface?
+
+=item Solution
+
+    show_error_box(title => "foo", message => "bar");
+
+    use Inline C => <<'END_OF_C_CODE';
+
+    void show_error_box(SV *unused, ...) {
+      Inline_Stack_Vars;
+      char *key;
+      int i;
+
+      // setup default values for parameters
+      int width = 800;
+      int height = 600;
+      char *title = NULL;
+      char *message = NULL;
+
+      // check for even number of args
+      if (Inline_Stack_Items % 2)
+        croak("Usage: show_error_box(key => value, ...).");
+
+      // step through key value pairs and assign parameter values
+      for (i = 0; i < Inline_Stack_Items; i+=2) {
+        key = SvPV_nolen(Inline_Stack_Item(i));
+        if (strEQ(key, "width")) {
+          width = SvIV(Inline_Stack_Item(i+1));
+        } else if (strEQ(key, "height")) {
+          height = SvIV(Inline_Stack_Item(i+1));
+        } else if (strEQ(key, "title")) {
+          title = SvPV_nolen(Inline_Stack_Item(i+1));
+        } else if (strEQ(key, "message")) {
+          message = SvPV_nolen(Inline_Stack_Item(i+1));
+        } else {
+          croak("options: Unknown parameter: \"%s\"", key);
+        }
+      }
+
+      // check required options title and message
+      if (title == NULL)
+        croak("options: required parameter title missing.");
+      if (message == NULL)
+        croak("options: required parameter message missing.");
+
+      // call underlying function
+      gfoo_show_error_box(title, message, width, height);
+    }
+
+    END_OF_C_CODE
+
+=item Discussion
+
+This function wraps the C function C<gfoo_show_error_box> which
+expects four arguments; title, message, width and height.  It allows
+users to specify these arguments using a key-value list.  It also
+allows users to not specify width and height and have them default to
+reasonable values.
+
+This function uses the C<Inline_Stack_> macros much like the previous
+example.  It steps through the list of parameters two at a time,
+examining the keys and assigning the values to C variables of the same
+name.
+
+After the parameters are all processed, the function checks that the
+required values have been filled in.  Finally, the function calls the
+wrapped function C<gfoo_show_error_box>.
+
+=item See Also
+
+=item Credits
+
+Sam Tregar <[EMAIL PROTECTED]>
+
+=back
+
+=cut --------------------------------------------------------------------------
+
 =head2 Multiple Return Values

 =over 4



Reply via email to