[英]Is it possible to call a 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 try below?
是否有可能将Fortran接口称为C ++中的重载函数,我在下面尝试?
This is the Fortran code: 这是Fortran代码:
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: 这是C ++代码:
#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.
或者只是为这两个extern C函数创建一个C ++泛型包装器。 You definitely cannot make Fortran to export the interface.
你绝对不能让Fortran导出界面。 Interface is just a description how to call the two subroutines under some name internally in Fortran.
接口只是描述如何在Fortran内部调用某些名称下的两个子程序。
This question importing interface module procedure from fortran into C is very similar. 这个问题从fortran到C的导入接口模块程序非常相似。 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.
Fortran泛型和C ++泛型不兼容。 And you have C between them which has no generics of similar type.
而且它们之间有C,没有相似类型的泛型。
Note: As @RichardCritten suggest you also should not pass by reference in an extern C
function. 注意:正如@RichardCritten建议你也不应该通过
extern C
函数中的引用传递。 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.
有关更多信息,请参阅C ++ by-reference参数和C链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.