Fortran API / lammps_extract_global

Please provide an example, where this causes a problem. I don’t see it.
I also cannot see how malloc() has any role in this. So please explain.

I tripped it by writing (in a not-yet-pushed implementation of id_name, which has a final argument buf_size declared int) something like this:

! ...
INTEGER(c_int) :: buf_size
TYPE(c_ptr) :: Cbuffer
! ...
buf_size = LEN(buffer) ! or LEN(buffer, KIND=c_int) to be safe
Cbuffer = lammps_malloc(buf_size)

Compiling that gives

      |     Cbuffer = lammps_malloc(buf_size)
      |              1
Error: Type mismatch in argument ‘size’ at (1); passed INTEGER(4) to INTEGER(8)

If instead I make buf_size of type INTEGER(c_size_t), then the call to lammps_id_name will have a similar problem. I can solve either problem relatively easily (e.g., Cbuffer = lammps_malloc(INT(buf_size, KIND=c_size_t)) or the reverse, or simply declare another variable Cbuf_size that’s of kind c_size_t, but it’s a question of whether it’s better to get around the “kind” changes or whether it’s better to change the C interface to use size_t rather than int for array lengths.

There should be no call to “lammps_malloc()”. Instead “buffer” should already be allocated outside of the Fortran module and then processed similar to how it is done in “lmp_get_os_info()”.

I actually refactored that yesterday to reduce code duplication, but I will modify that refactorization to reduce calls to malloc (which is probably a good idea anyway).

My original question should have been, “Should the C interface variables that code for string length be of type size_t instead of int?” Based on your replies, I gather that the answer is “no.” I also didn’t remember at the time I first asked that size_t requires the stddef.h header, and that would violate the desire to keep header requirements on library.h to a minimum (so…“no” again).


The Fortran interface should only allocate memory via the C malloc() interface call when the resulting pointer is supposed to be freed by LAMMPS internally. Otherwise buffers should always be allocated and freed from Fortran. Similarly, the interface to C free() is only needed because some calls in the library interface will create a buffer that has to be freed by the “consumer”.

That is the paradigm I have been using with the Fortran API.