如何使用C_PTR具有一个具有不同类型参数的ForTran函数?
我阅读了 最佳实践 。
我想在中使用类型(C_PTR)指针中描述的内容中使用某些内容,
但我有问题。我概述了我尝试做的事情。我希望这足以理解。否则,让我知道,我将发布一个完整的例子。
我有两种类型,我将一种或另一种类型称为同一子例程。我子例程的第一个参数是一个整数,指示哪种是第二个参数的类型(type1_t或type2_t),
type type1_t
real :: a, b
integer :: c
end type1_t
type type2_t
real :: a,e
integer :: b,c,d
end type2_t
type(type1_t) :: type1
! ... init of type1
type(type2_t) :: type2
! ... init of type2_t
call myfoo(1,c_loc(type_1))
call myfoo(2,c_loc(type_2))
但是现在,我对MyFoo中的声明有问题,因为声明必须在说明之前在Fortran中完成。
我知道以下代码不起作用:
subroutine myfoo(i, params)
integer, intent(in) :: i
type(c_ptr), intent(in) :: params
if (i == 1) then
type(type1_t), pointer :: pars
elseif (i ==2) then
type(type2_t), pointer :: pars
endif
call c_f_pointer(params, pars)
! do some stuff with pars (there are common parts of code either the dummy args is type_1 or type_2). For example, the line above.
end subroutine myfoo
如果我使用块构造,我会遇到问题,因为该变量在块末尾消失。
如何使用C_PTR解决它?
I read the section Type Casting in Callbacks of the article Fortran Best practices.
I would like to use in my program something as described in Using type(c_ptr) Pointer
But I have a problem. I give an outline of what I try to do. I hope it will be sufficient to understand. Otherwise, let me know, I will post a full example.
I have two types and I call the same subroutine with one or the other type. The first parameter of my subroutine is an integer to indicate which is the type of the second parameter (type1_t or type2_t)
type type1_t
real :: a, b
integer :: c
end type1_t
type type2_t
real :: a,e
integer :: b,c,d
end type2_t
type(type1_t) :: type1
! ... init of type1
type(type2_t) :: type2
! ... init of type2_t
call myfoo(1,c_loc(type_1))
call myfoo(2,c_loc(type_2))
But now, I have a problem with the declaration in myfoo because the declaration must be done in fortran before instructions.
I know that the following code does not work :
subroutine myfoo(i, params)
integer, intent(in) :: i
type(c_ptr), intent(in) :: params
if (i == 1) then
type(type1_t), pointer :: pars
elseif (i ==2) then
type(type2_t), pointer :: pars
endif
call c_f_pointer(params, pars)
! do some stuff with pars (there are common parts of code either the dummy args is type_1 or type_2). For example, the line above.
end subroutine myfoo
If I use a block construct, I will have a problem because the variable disappears at the end of the block.
How can I solve it using c_ptr?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的一种简单方法是将特定于类型的代码放在模块中的两个单独的例程中,并使用接口绑定它们,因此编译器将根据输入上提供的变量的类型选择正确的子例程:
A simple way to accomplish this is to put type-specific code in two separate routines in a module, and bind them using an interface, so the compiler will pick the right subroutine based on the type of the variable provided on input: