Re: Interfacing C procedure using an array as parameter ?

From: Xavier Leroy (Xavier.Leroy@inria.fr)
Date: Tue Apr 29 1997 - 17:42:16 MET DST


From: Xavier Leroy <Xavier.Leroy@inria.fr>
Message-Id: <199704291542.RAA03587@pauillac.inria.fr>
Subject: Re: Interfacing C procedure using an array as parameter ?
In-Reply-To: <3364B837.4925@parc.anglia.ac.uk> from "Vincent B.G. Leleu" at "Apr 28, 97 03:46:15 pm"
To: vincent@parc.anglia.ac.uk (Vincent B.G. Leleu)
Date: Tue, 29 Apr 1997 17:42:16 +0200 (MET DST)

> This is the first time I interface C/OCaml and also I have
> a problem : How do I use a parameter which is a pointer
> on the beginning of an integer array ?

To get you started, here are functions to convert between a C integer
array and a Caml integer array. (Warning: untested code ahead.)

value c_intarray_to_caml_intarray(int * carray, unsigned int nelts)
{
  value mlarray;
  int i;

  mlarray = nelts < Max_young_wosize ? alloc(nelts, 0) : alloc_shr(nelts, 0);
  for (i = 0; i < nelts; i++) Field(mlarray, i) = Val_int(carray[i]);
  return mlarray;
}

int caml_intarray_to_c_intarray(value mlarray,
                                int ** carray /*out parameter*/,
                                unsigned int * nelts /*out parameter*/)
{
  unsigned int len;
  int * p;
  int i;

  len = Wosize_val(mlarray);
  p = malloc(len * sizeof(int));
  if (p == NULL) return -1;
  for (i = 0; i < len; i++) p[i] = Int_val(Field(mlarray, i));
  *carray = p;
  *nelts = len;
  return 0;
}

Hope this helps,

- Xavier Leroy



This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:10 MET