繁体   English   中英

是否可以从C ++调用Fortran接口

[英]Is it possible to call a Fortran interface from C++

我有以下不编译的代码。 是否有可能将Fortran接口称为C ++中的重载函数,我在下面尝试?

这是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

这是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;
}

不,这是无法避免的。 但是你可以实例化一个模板来调用这两个模板。 或者只是为这两个extern C函数创建一个C ++泛型包装器。 你绝对不能让Fortran导出界面。 接口只是描述如何在Fortran内部调用某些名称下的两个子程序。

这个问题从fortran到C的导入接口模块程序非常相似。 我甚至最初把你的作为副本关闭了,但后来我改变主意,因为尝试的解决方案略有不同。

但原则是一样的。 Fortran泛型和C ++泛型不兼容。 而且它们之间有C,没有相似类型的泛型。

注意:正如@RichardCritten建议你也不应该通过extern C函数中的引用传递。 编译器可能编译它并实现为按值传递指针,但不保证。 只需传递一个指针。 有关更多信息,请参阅C ++ by-reference参数和C链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM