hombit
hombit

Reputation: 151

Using of Fortran function in C causes seg fault on start up

I try to implement the basic example of Fortran derived type C binding using iso_c_binding.

circle.f90

module class_circle

use iso_c_binding

implicit none
private
public :: Circle, init_Circle

real(c_double), parameter :: pi = 3.1415926535897932384626433832795

type, bind(C) :: Circle
   real(c_double) :: radius = 1
   real(c_double) :: area
end type Circle

contains

type(Circle) function init_Circle(r) bind(C, name='init_Circle')
   implicit none
   real(c_double), intent(in) :: r

   init_Circle%radius = r
   init_Circle%area = pi * r * r
end function init_Circle

end module class_circle

main_c.c

#include <stdio.h>

struct circle {
    double radius, area;
};

struct circle* init_Circle(double* r);

int main() {
    double r = 10;
    struct circle* c = init_Circle(&r);
    double area = c->area;
    printf("%lg", area);
    return 0;
}

Compilation:

gcc -g -c main_c.c -o main_c.o
gfortran -g -c circle.f90
gcc -g main_c.o circle.o -o main_c

Result:

[1]    99081 segmentation fault  ./main_c

Upvotes: 0

Views: 116

Answers (1)

Your C function prototype says that the function returns a pointer to a struct

struct circle* init_Circle(double* r);

but the Fortran function returns a struct directly

type(Circle) function init_Circle(r) bind(C, name='init_Circle')

you must make this consistent.

Note also the comment of @evets, no matter how many digits 3.1415926535897932384626433832795 has, it is only a single precision number. And the function and its call from C can be made simpler with the value attribute.

module class_circle

use iso_c_binding

implicit none
private
public :: Circle, init_Circle

real(c_double), parameter :: pi = 3.1415926535897932384626433832795_c_double

type, bind(C) :: Circle
   real(c_double) :: radius = 1
   real(c_double) :: area
end type Circle

contains

type(Circle) function init_Circle(r) bind(C, name='init_Circle')
   implicit none
   real(c_double), value :: r

   init_Circle%radius = r
   init_Circle%area = pi * r * r
end function init_Circle

end module class_circle

.

#include <stdio.h>

struct circle {
    double radius, area;
};

struct circle init_Circle(double r);

int main() {
    double r = 10;
    struct circle c = init_Circle(r);
    double area = c.area;
    printf("%lg", area);
    return 0;
}

.

> gfortran circle.f90 main_c.c
> ./a.out 
314.159

Upvotes: 2

Related Questions