I have the following code that does not compile. Is it possible to call the Fortran interface as overloaded functions in C++, as I try 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;
}
No, it cannot be avoided. But you can instantiate a template to call the two. Or just make a C++ generic wrapper to those two extern C functions. You definitely cannot make Fortran to export the interface. Interface is just a description how to call the two subroutines under some name internally in Fortran.
This question importing interface module procedure from fortran into C is very similar. I even originally closed yours as a duplicate, but then I changed my mind because the attempted solution is slightly different.
But the principle is the same. Fortran generics and C++ generics are not compatible. And you have C between them which has no generics of similar type.
Note: As @RichardCritten suggest you also should not pass by reference in an extern C
function. The compiler probably compiles it and implements as passing a pointer by value, but it is not guaranteed. Just pass a pointer. See C++ by-reference argument and C linkage for more.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.