Is it possible to call Fortran interface from C ++
I have the following code that does not compile. Is it possible to call the Fortran interface as overloaded functions in C ++ as I am trying to do below?
This is the Fortran code:
module functions
use, intrinsic :: iso_c_binding, only : c_double, c_int
implicit none
interface increment bind(c, name="increment")
module procedure increment_int, increment_double
end interface
contains
subroutine increment_int(a, b)
integer(c_int), intent(inout) :: a
integer(c_int), value :: b
a = a + b
end subroutine
subroutine increment_double(a, b)
real(c_double), intent(inout) :: a
real(c_double), value :: b
a = a + b
end subroutine
end module functions
And this is the C ++ code:
#include <iostream>
namespace
{
extern "C" void increment(int&, int);
extern "C" void increment(double&, double);
}
int main()
{
int a = 6;
const int b = 2;
double c = 6.;
const int d = 2.;
increment(a, b);
increment(c, d);
std::cout << "a = " << a << std::endl;
std::cout << "c = " << c << std::endl;
return 0;
}
source to share
No, it cannot be avoided. But you can create a template to call two. Or just create a common C ++ wrapper for these two external C functions. You definitely can't get Fortran to export the interface. An interface is simply a description of how to call two subroutines under a certain name within Fortran.
This question importing an interface module procedure from fortran into C is very similar. I even initially closed yours as a duplicate, but then I changed my mind because trying to solve it is slightly different.
But the principle is the same. C ++ formatted generics and generic files are incompatible. And you have a C in between, which has no generics of this type.
Note. As @RichardCritten suggests you don't pass by reference in functions either extern C
. The compiler will probably compile it and implement it as passing a pointer by value, but it is not guaranteed. Just pass the pointer. See C ++ reference argument and C reference for details .
source to share