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++,它是不起作用的。下面的示例代码演示了缝合
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,但得到了广泛支持。
相关文章:
- 如何使用默认参数等选择模板专业化
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 何时提供默认参数作为模板参数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 函数不接受 X 参数,函数使用默认参数
- initializer_list具有默认参数的构造函数
- C++ 带有默认参数的结构,可选择在构造函数中更改
- 为什么C++构造函数在继承中需要默认参数?
- 必须非常量别名参数及其默认参数常量
- C++ 默认参数使用其他参数
- 组合函数参数包和默认参数
- 如何定义 Vector2f 的默认参数?[SFML]
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何设置默认参数以防用户不输入另一个参数
- 结构 c++ 中的默认参数
- 构造函数委托与默认参数
- 默认参数和函数指针作为函数参数C++
- 如何在继承层次结构中调用具有默认参数的构造函数?