The following test program causes segment fault when using whole array assigment in mod_a.f90, but works well when using do loops.
f.h
#if !defined(F_H)
#define F_H
extern "C" {
int create2d(float** v, int n);
};
#endif
f.cc
#include "f.h"
int create2d(float** v, int n)
{
int i;
*v = new float[n * n];
for(i = 0; i < n * n; ++i)
(*v)[i] =1.0;
return n;
}
mod_f.f90
module f
use, intrinsic :: iso_c_binding
implicit none
interface
function create2d(v, n) result(r) bind(c)
import :: c_ptr, c_int
type(c_ptr), intent(out) :: v
integer(c_int), value :: n
integer(c_int) :: r
end function create2d
end interface
end module f
mod_a.f90
module a
use, intrinsic :: iso_c_binding
use f
type :: a
real, dimension(:,:), allocatable :: v
end type
contains
subroutine a_init(this)
type(a) :: this
type(c_ptr) :: cptr
real(c_float), dimension(:,:), pointer :: fptr
integer :: n, i, j
n = 5
n = create2d(cptr, n)
allocate(this%v(n, n))
call c_f_pointer(cptr, fptr, [n, n])
this%v = fptr ! causes segement fault
! do j = 1, n ! ok when using do loops
! do i = 1, n
! this%v(i, j) = fptr(i, j)
! end do
! end do
print *, "this%v(1,1)", this%v(1,1)
end subroutine a_init
end module a
test.f90
program test
use a
implicit none
type(a) :: aa
call a_init(aa)
end program test