簡體   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