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

typedef return_type (*funcHandle)(); /* function pointer type */

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

/* for saving the function pointer from Ch space */
static void *setFunction2_chdl_funptr; 

EXPORTCH void setFunction2_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 Ch function pointer  */
  handle_ch = Ch_VaArg(interp, ap, funcHandle);   
  setFunction2_chdl_funptr = (void *)handle_ch;

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

  setFunction2(arg1, handle_c);

  Ch_VaEnd(interp, ap);
}

static return_type setFunction2_chdl_funarg() {
  return_type retval;

  /* Call Ch address space function by its address */
  Ch_CallFuncByAddr(interp, setFunction2_chdl_funptr, &retval);
  return retval;
}
