在下面的代码中,我检查int* j
的内部和之后的Mystruct
的{{1}}的地址。地址在每种情况下都不同。有什么问题吗?
C ++
Mystruct
Fortran驱动程序
struct Mystruct
{
int* j;
Mystruct()
{
j = new int;
*j = 8;
check_address();
}
void check_address()
{
std::cout << j << std::endl;
}
};
typedef void* OpaqueObject;
extern "C"
{
OpaqueObject allocate_mystruct()
{
Mystruct* ms = new Mystruct();
return reinterpret_cast<OpaqueObject>(ms);
}
void check_address(OpaqueObject** oo)
{
Mystruct *ms = (Mystruct*)(**oo);
ms->check_address();
}
}
Fortran模块
program main
use mpi
use mymodule, only : f_allocate_mystruct, f_check_address
IMPLICIT NONE
integer error
call MPI_Init(error)
call f_allocate_mystruct()
call f_check_address()
call MPI_Finalize (error)
end
编辑
根据一些程序员dude的评论修改module mymodule
use mpi
use, intrinsic :: ISO_C_Binding, only: c_ptr, c_null_ptr
implicit none
private
interface
function allocate_mystruct() result(optr) bind(C, name="allocate_mystruct")
import c_ptr
implicit none
type(c_ptr) :: optr
end function allocate_mystruct
subroutine check_address(optr) bind(C, name="check_address")
import :: c_ptr
implicit none
type(c_ptr), intent(in) :: optr
end subroutine check_address
end interface
type(c_ptr), save :: c_mystruct = c_null_ptr
public :: f_allocate_mystruct, f_check_address
CONTAINS
subroutine f_check_address()
if(c_associated(c_mystruct)) then
call check_address(c_mystruct);
end if
end subroutine f_check_address
subroutine f_allocate_mystruct()
c_mystruct = allocate_mystruct()
end subroutine f_allocate_mystruct
end module mymodule
接口解决了该问题。
check_address