在 Visual Studio 中将可变长度 c 字符串转换为 Fortran 字符串

标签 c arrays string visual-studio fortran

我需要将 C 字符串转换为 Fortran 字符串。当我在 Visual Studio 2012 中使用 Intel Visual Fortran Composer XE 2013 调试示例代码时,我遇到了几个问题:

1) 我在调试器中看不到延迟长度可分配字符变量 (str) 的值。

2) 当在代码中放置断点时,分配此变量类型会导致 fCode.pdb 文件锁定。释放文件的唯一方法是关闭句柄(通过 Process Explorer)或关闭 IDE。

我在代码中遗漏了什么吗?释放内存?有没有更简洁的方法来进行转换?

C代码

int main ( void ) {

    char* cstr = "BP1000";

    c_to_f(cstr);

    return 0;
}

Fortran 代码

module mytest
    contains

    subroutine c_to_f(cstr)  BIND(C, name="c_to_f")
    use, intrinsic :: iso_c_binding    
    !DEC$ ATTRIBUTES DLLEXPORT :: c_to_f

    character(kind=C_CHAR, len=1), intent(IN) :: cstr(*)    
    character(:), allocatable :: str

    str = c_to_f_string(cstr)

    end subroutine c_to_f  

    function c_to_f_string(s) result(str)
      use, intrinsic :: iso_c_binding
      character(kind=C_CHAR, len=1), intent(IN) :: s(*)
      character(:), allocatable  :: str
      integer i, nchars
      i = 1
      do
         if (s(i) == c_null_char) exit
         i = i + 1
      end do
      nchars = i - 1  ! Exclude null character from Fortran string
      allocate(character(len=nchars) :: str)
      str = transfer(s(1:nchars), str)
    end function c_to_f_string

end module mytest   

最佳答案

问题中不清楚C代码如何使用Fortran字符串?

如果字符串来自 C 函数:

const char *getcstr(void)
{
    return "Hello!";
}

这是完整的 Fortran 程序,它调用 C 函数,将结果转换为 Fortran 字符串,然后打印:

implicit none

interface
    function getcstr() bind(c, name="getcstr")
        use, intrinsic :: iso_c_binding
        type(c_ptr) getcstr
    end
end interface

print *, cstr2f(getcstr())

contains
    function cstr2f(s)
        use, intrinsic :: iso_c_binding
        interface
            pure function strlen(s) bind(c, name="strlen")
                use, intrinsic :: iso_c_binding
                type(c_ptr), intent(in), value :: s
                integer(c_size_t) strlen
            end
        end interface
        type(c_ptr) s
        character(kind=c_char, len=strlen(s)), pointer :: cstr2f

        call c_f_pointer(s, cstr2f)
    end
end

关于在 Visual Studio 中将可变长度 c 字符串转换为 Fortran 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365293/

相关文章:

c - fscanf() 的哪个正则表达式将忽略一行中的任何字符/字符串/特殊字符?

java - java中术语 "parse"的起源是什么?

string - 在Hibernate中将String转换为Clob,反之亦然

c - Flex & Bison : "true" being interpreted as and ID

c - ZeroMemory 函数在 windows.h 中给我错误?

c - C语言的简单时间复杂度

c# - 用数组填充 DataTable

java - 数组操作 : HackerRank Questions : JAVA

c - 从函数返回错误的数组值

php - 来自具有最常见单词的多个字符串的新字符串