簡體   English   中英

C ++和混合編程中指針的默認參數

[英]Default arguments for pointer in C++ and mixed programming

可以使用以下代碼演示C ++中指針的默認參數的用法

#include <iostream>

void myfunc_(int var, double* arr = 0) {
  if (arr == 0) {
    std::cout << "1 arg" << std::endl;
  } else {
    std::cout << "2 arg" << std::endl;
  }
}

int main() {
  myfunc(1);
  double *arr = new double[2];
  myfunc(1, arr);
}

在這種情況下,程序的輸出是

1 arg
2 arg

另一方面,如果我嘗試將可選參數從Fortran傳遞給C ++,它就不起作用。 以下示例代碼演示了sutiation

myfunc.cpp

#include <iostream>

extern "C" void myfunc_(int var, double* arr = 0) {
  if (arr == 0) {
    std::cout << "1 arg" << std::endl;
  } else {
    std::cout << "2 arg" << std::endl;
  }
} 

Fortran主程序

program main
use iso_c_binding

real*8 :: arr(2)

call myfunc(1)
call myfunc(1, arr)
end program main

並且可以使用以下命令編譯混合代碼(Fortran和C ++),而不會出現任何錯誤

g++ -c myfunc.cpp
gfortran -o main.x myfunc.o main.f90 -lstdc++ -lc++ 

但程序打印

2 arg
2 arg

在這種情況下。 那么,這個問題有什么解決方案嗎? 我在這里錯過了什么嗎? 我認為在混合編程中使用默認參數並不像預期的那樣工作,但我現在需要建議。

正如評論中指出的那樣, extern "C"函數中不能包含參數的默認值。 但是,您可以在函數的Fortran界面中使用可選參數,並以您希望的方式調用它:

#include <iostream>
extern "C" void myfunc(int var, double* arr) { //removed the = 0 and renamed to myfunc
  if (arr == 0) {
    std::cout << "1 arg" << std::endl;
  } else {
    std::cout << "2 arg" << std::endl;
  }
}

在Fortran中創建一個描述C(C ++)函數的接口:

program main
use iso_c_binding

interface
  subroutine myfunc(var, arr) bind(C, name="myfunc")  
    use iso_c_binding
    integer(c_int), value :: var
    real(c_double), optional :: arr(*)
  end subroutine
end interface

!C_double comes from iso_c_binding
real(c_double):: arr(2)

call myfunc(1_c_int)
call myfunc(1_c_int, arr)
end program main

關鍵是界面中的optional屬性。 如果不提供可選數組,則會傳遞空指針。

還要注意var參數的value屬性。 這是必要的,因為C ++函數按值接受參數。

注意:這是作為Fortran 2008標准的TS的最新添加,但得到了廣泛的支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM