从go调用fortran库的最小示例

时间:2018-11-18 02:02:31

标签: go fortran ffi

我正在寻找这两种语言之间的FFI的最小示例,这是一个调用Fortran库的Go程序的非常简单的问候世界。

我想强调的是,我不是在寻找外部资源,建议或教程,而是在golang中仅找到最少的代码段,而在Fortran中则只是找到相应的格式。

此站点上有很多示例:

Go-> Fortran示例将与这些示例保持一致,并且对其他开发人员很有用。

修改以解决重复声明

这个问题有一个答案,与之相连的那个答案没有答案。将问题关闭并重定向为可能以-5票关闭的重复项对stackoverflow用户没有用,尽管两者都提出了合理的问题。

1 个答案:

答案 0 :(得分:5)

cgo(https://golang.org/cmd/cgo/)似乎提供了调用C的功能。因此,我尝试使用它来调用Fortran(在OSX10.11上使用go-1.11 + gfortran-8.2),这似乎可以正常工作对于这个简单的程序...

main.go:

package main

// #cgo LDFLAGS: mylib.o -L/usr/local/Cellar/gcc/8.2.0/lib/gcc/8 -lgfortran
// void hello();
// int  fort_mult( int );
// void array_test1 ( double*, int* );
// void array_test2_( double*, int* );
import "C"
import "fmt"

func main() {
    // print a message
    C.hello()

    // pass a value
    fmt.Println( "val = ", C.fort_mult( 10 ) )

    k := C.int( 777 )
    fmt.Println( "val = ", C.fort_mult( k ) )

    // pass an array
    a := []C.double {1, 2, 3, 4, 5.5555}
    n := C.int( len(a) )

    C.array_test1( &a[0], &n )  // pass addresses
    fmt.Println( a )

    C.array_test2_( &a[0], &n )  // no use of iso_c_binding
    fmt.Println( a )
}

mylib.f90:

subroutine hello() bind(C)
    print *, "Hello from Fortran"
end subroutine

function mult( x ) result( y ) bind(C,name="fort_mult")  ! can use a different name
    use iso_c_binding, only: c_int
    integer(c_int), value :: x
    integer(c_int) :: y

    y = x * 10
end function

subroutine array_test1( arr, n ) bind(C)   ! use iso_c_binding
    use iso_c_binding, only: c_int, c_double
    integer(c_int) :: n
    real(c_double) :: arr( n )

    arr(:) = arr(:) * 100.0d0
end subroutine

subroutine array_test2( arr, n ) ! no use of iso_c_binding (e.g. for legacy codes)
    integer :: n
    double precision :: arr( n )   ! or real(8) etc

    arr(:) = arr(:) * 2.0d0
end subroutine

编译:

gfortran -c mylib.f90
go build main.go
./main

结果:

 Hello from Fortran
val =  100
val =  7770
[100 200 300 400 555.5500000000001]
[200 400 600 800 1111.1000000000001]
相关问题