gpt4 book ai didi

c - 如何从由 iso_c_binding 的 Fortran 调用的 C 函数接收字符串?

转载 作者:行者123 更新时间:2023-12-04 04:21:17 25 4
gpt4 key购买 nike

我想从 Fortran 调用 C 函数并接收在 C 函数中定义的字符串。我搜索过,但到目前为止我找不到一个有效的、直接的答案。

实际上我找到了一个解决方法:接收一个字符数组,然后使用内部函数 transfer将结果放入 Fortran 字符串中。
这是我的工作代码。

Fortran主程序:

program pr
implicit none
character(200) :: stringa

call strfromc(stringa)
write (6,*) 'FPR stringa: "', trim(stringa),'"'

stop
end program pr

Fortran子程序:
subroutine strfromc(stringa)
use iso_c_binding
implicit none

character(200) :: stringa

interface
subroutine getstrfromc(ld,d) bind(c,name='getString')
import :: c_int, c_ptr
integer(c_int) :: ld
type(c_ptr), value :: d
end subroutine getstrfromc
end interface

! declare a character array of type c_char and sufficient length:
character(c_char), dimension(200), target :: d1

integer :: ld1 ! will contain the string length
integer :: i

! the C pointer of character array d1 is passed:
call getstrfromc(ld1, c_loc(d1))

! read the first ld1 elements of array d1 as a character string, which will be returned:
stringa= transfer(d1(1:ld1), stringa)

write (6,*) 'SF d1: ', (d1(i),i=1,ld1)
write (6,*) 'SF stringa: "', trim(stringa),'"'
write (6,*) ''

return
end subroutine

C函数:
#include <stdio.h>
#include <string.h>

void getString(int * lw, char * w) {
printf("Enter a string:\n");
scanf("%[^\n]", w); //scanning the whole string, including the white spaces

*lw= strlen(w);

printf("C: w: %s\n", w);
printf("C: lw: %d\n", *lw);
printf("\n");

return;
}

任何人都可以提出更直接的方法吗?

最佳答案

为什么不简单地使用 C_CHAR种类?我“压缩”了你的代码:

program main
use, intrinsic :: iso_c_binding, only: C_INT, C_CHAR
implicit none
integer :: lw ! will contain the string length
character(256) :: w = "" ! will contain the string; Initialize to empty

! C interface
interface
subroutine getstrfromc( lw, w ) bind( c, name='getString' )
import :: C_INT, C_CHAR
implicit none
integer(C_INT), intent(out) :: lw
character(C_CHAR), intent(out) :: w(*)
end subroutine getstrfromc
end interface

! In Fortran variables are passed by default as "pointers".
call getstrfromc( lw, w )

! Write string
write (*,*) "Fortran: w: ", trim(w)
write (*,*) "Fortran: lw:", lw

end program main

C 函数保持不变。

关于c - 如何从由 iso_c_binding 的 Fortran 调用的 C 函数接收字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59247212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com