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

int callchvla_2d(int (*fun)(int a[&][&])) {
  void *handle, *fptr;
  int retval;

  handle = dlopen("libcallchvla.dl", RTLD_LAZY);
  if(handle == NULL) {
     printf("Error: %s(): dlopen(): %s\n", __func__, dlerror());
     return -1;
  }
  fptr = dlsym(handle, "callchvla_2d_chdl");
  if(fptr == NULL)  {
     printf("Error: %s(): dlsym(): %s\n", __func__, dlerror());
     return -1;
  }

  dlrunfun(fptr, &retval, callchvla_2d, fun);
 
  if(dlclose(handle)!=0) {
     printf("Error: %s(): dlclose(): %s\n", __func__, dlerror());
     return -1;
  }
  return retval;
}

int sum2d(array int a[&][&]) { /* function to be called from C space */
  int i, j, retval = 0;

  array int ext[2] = shape(a);
  int n = ext[0], m = ext[1];
  array int aa[n][m];
  aa = a;

  printf("ext[0] = %d\n", ext[0]);
  printf("ext[1] = %d\n", ext[1]);
  for(i = 0; i < n; i++)
    for(j = 0; j < m; j++)
       retval += aa[i][j];

  return retval;
}

int main() {
  int sum_ret;
  int a[3][4] = { 1, 2, 3, 4,
                  5, 6, 7, 8,
                  9, 10, 11, 12 };

  sum_ret = sum2d(a);
  printf("sum2d has been called from Ch space and returned %d\n\n", sum_ret);

  callchvla_2d(sum2d); 
  return 0;
}
