Fortran / C互操作性程序在C_LOC崩溃

时间:2017-03-21 18:59:08

标签: c++ c pointers fortran structure

之前我曾问过一个相关的问题。 Passing a structured data type from Fortran to C++

但它与以下问题重复: Fortran derived types containing pointers to be accessible from C

我创建了一个简单的例子,但是我的程序在调用C_LOC

时崩溃了

这是完整的示例(简短,自包含,可执行)

档案:mydata.f90

module mydata

type mytype
    integer :: loaded
    integer :: status
end type mytype

CONTAINS

FUNCTION GetHandle() RESULT(handle) BIND(C, NAME = 'GetHandle')
    USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR, C_LOC
    TYPE(C_PTR) :: handle
    TYPE(mytype), POINTER :: p
    ALLOCATE(p)
    p % loaded = 1122334455
    p % status = 1234567890
    write(*, *) 'GetHandle:p_addr = ', loc(p)
    write(*, *) 'GetHandle:p%loaded = ', p % loaded
    write(*, *) 'GetHandle:p%status = ', p % status
    handle = C_LOC(p)
END FUNCTION GetHandle

SUBROUTINE ReleaseHandle(handle) BIND(C, NAME = 'ReleaseHandle')
    USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR, C_F_POINTER
    TYPE(C_PTR), INTENT(IN), VALUE :: handle
    TYPE(mytype), POINTER :: p
    CALL C_F_POINTER(handle, p)
    DEALLOCATE(p)
END SUBROUTINE ReleaseHandle

end module mydata

档案:dostuff.f90

subroutine STUFF(handle, ier) BIND(C, NAME = 'STUFF')
    use mydata
    USE, INTRINSIC :: ISO_C_BINDING
    implicit none
    TYPE(C_PTR), INTENT(IN), VALUE :: handle
    TYPE(mytype), POINTER :: p
    INTEGER :: ier

    CALL C_F_POINTER(handle, p)
    write(*, *) 'FITC:p_addr = ', loc(p)
    write(*, *) 'FITC:s%loaded = ', p % loaded
    write(*, *) 'FITC:s%status = ', p % status
end

文件:main.cpp

#include <cstdio>
#include <cstdlib>

using namespace std;

#ifdef __cplusplus
extern "C" {
#endif
    void* GetHandle();
    void ReleaseHandle(void* handle);
    void STUFF(void *handle, int *ierr);
#ifdef __cplusplus
}
#endif

int main(int argc, const char* const argv[]) {
    void *handle;
    int ierr = 0;
    handle = GetHandle();
    STUFF(handle, &ierr);
    ReleaseHandle(handle);
    return 0;
}

我在Linux 64位上使用intel C ++ / fortran编译器。

如何修复错误?

编辑:确切的错误消息如下(gdb输出)。

Program received signal SIGSEGV, Segmentation fault.
0x00000000004031ff in MYDATA::gethandle (handle=<error reading variable: Cannot access memory at address 0x1>) at mydata.f90:20
20              handle = C_LOC(p)
(gdb) bt
#0  0x00000000004031ff in MYDATA::gethandle (handle=<error reading variable: Cannot access memory at address 0x1>) at mydata.f90:20
#1  0x0000000000402efa in main (argc=1, argv=0x7fffffffdf88) at main.cpp:19

没有gdb,只有内存故障导致c崩溃。

0 个答案:

没有答案