cfortraninteropfortran-iso-c-binding

How to declare pointer-of-pointer using iso_c_binding?


I am writing an iso_c_binding in Fortran to call a C-function with the below prototype

int zmat_run(
    const size_t inputsize,
    unsigned char *inputstr, 
    size_t *outputsize, 
    unsigned char **outputbuf,
    const int zipid, 
    int *ret, 
    const int iscompress
);

My question is how do I declare unsigned char **outputbuf, a pointer that is used inside the c-function to allocate output buffer, in this interface?

Also, what data type I should be using in Fortran as the real parameter to pass to this outputbuf parameter? should it be allocatable? (if it is allocated inside the c-function)?

I currently drafted this module, but haven't tested it (I doubt it will work).

module zmatlib
  use iso_c_binding, only: c_char, c_size_t, c_ptr, C_NULL_CHAR
  interface
    integer(c_int) function zmat_run(inputsize, inputbuf, outputsize, outputbuf, zipid, ret, level) bind(C, name="zmat_run")
      use iso_c_binding
      integer(c_size_t), value :: inputsize
      integer(c_int), value :: zipid, level
      integer(c_size_t),  intent(out) :: outputsize
      integer(c_int),  intent(out) :: ret
      character(kind=c_char),  intent(in)  :: inputbuf(*)
      character pointer(c_ptr),intent(out) :: outputbuf
    end function zmat_run
  end interface
end module

Solution

  • Try type (C_PTR), intent (out). Then you will need to use Fortran function c_f_pointer to associate the C pointer with a Fortran pointer. Probably of type C_CHAR.