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

int chcallfuncbyaddr_1(int (*func)(int a[:], int b[:][:])) {
  void *handle, *fptr;
  int retval;

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

  fptr = dlsym(handle, "chcallfuncbyaddr_1_chdl");
  if(fptr == NULL)  {
     printf("Error: %s(): dlsym(): %s\n", __func__, dlerror());
     return -1;
  }

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

  return retval;
}

int func(int a[:], int b[:][:]) {  /* a and b are arrays of assumed-shape*/
  int j, k;
  int n = (int) shape(a);
  array int dim[2] = shape(b);
  int n1 = dim[0], m1 = dim[1];

  printf("The dimensions, numbers of elements and values of array a and b \
in func is:\n");
  printf("n  = %d\n", n);
  printf("n1 = %d\n", n1);
  printf("m1 = %d\n", m1);
  for(j=0; j<n; j++) {
    printf("a[%i] = %d\n", j, a[j]);
    a[j] *= 2;
  }
  for(j=0; j<n1; j++) {
    for(k=0; k<m1; k++) {
      printf("b[%i][%i] = %d\n", j, k, b[j][k]);
      b[j][k] *= 2;
    }
  }  
  return 0;
}

int main() {
  chcallfuncbyaddr_1(func);
}
