![](/img/trans.png)
[英]Default parameter and function pointer as function arguments 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.