/* Copyright (c) 2001-2009 by SoftIntegration, Inc. All Rights Reserved */
#include<ch.h>
#include<stdio.h>
/* ... */

/* define function pointer type with argument of data_type2 
   and return value of return_type */
typedef return_type (*funcHandle)(data_type2); 

static ChInterp_t interp;
/* C function to replace the Ch function pointer */
static return_type setFunction4_chdl_funarg(data_type2 arg2); 

/* save the function pointer from the Ch space */
static void *setFunction4_chdl_funptr; 

EXPORTCH void setFunction4_chdl(void *varg) {
  ChVaList_t ap;
  data_type1 arg1;
  funcHandle handle_ch, handle_c = NULL;

  Ch_VaStart(interp, ap, varg);
  arg1 = Ch_VaArg(interp, ap, data_type1);   /* get 1st argument  */
  /* get and save function pointer from Ch space  */
  handle_ch = Ch_VaArg(interp, ap, funcHandle);   
  setFunction4_chdl_funptr = (void *)handle_ch;

  /* replace the Ch function pointer with the C one,
     the NULL pointer can't be replaced */
  if(handle_ch != NULL) {
    handle_c = (funcHandle)setFunction4_chdl_funarg;
  }

  setFunction4(arg1, handle_c);

  Ch_VaEnd(interp, ap);
}

static return_type setFunction4_chdl_funarg(data_type2 arg2) {
  return_type retval; 

  /* Call Ch function by its address which has argument arg2, 
     and return a value */
  Ch_CallFuncByAddr(interp, setFunction4_chdl_funptr, &retval, arg2);

  return retval;
}
