用FORTRAN ISO_C_BINDING-C桥梁字符串数组 [英] Arrays of strings in fortran-C bridges using iso_c_binding

查看:1346
本文介绍了用FORTRAN ISO_C_BINDING-C桥梁字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写code,将调用来自Fortran语言使用Fortran内模块ISO_C_BINDING的C函数(在FORTRAN 2003年推出,并在gfortran和ifort的新版本中实现)。

I'm writing code that will call a C function from Fortran using the Fortran intrinsic module ISO_C_BINDING (introduced in fortran 2003 and implemented in newer versions of gfortran and ifort).

这答案几乎是我所需要的: http://stackoverflow.com/a/7964302/989692

This answer is almost what I need: http://stackoverflow.com/a/7964302/989692

我不能完全得到我的头周围有什么接口声明,我应该用Fortran使用C函数,看起来像这样:

I can't quite get my head around what interface declaration I should use in Fortran for a C function that looks like this:

int use_array(int n, char * array[]){
    int i;
    for(i=0; i<n; i++){
        printf("Item %d = %s\n",i,array[i]);
    }
    return n;
}

我不清楚该声明应该是什么在年底的Fortran接口:

I'm not clear what the declaration should be for the interface on the Fortran end:

interface
    function use_array(n, x) bind(C)
        use iso_c_binding
        integer (c_int) use_array
        integer (c_int), value :: n
        character(c_char) WHAT_SHOULD_GO_HERE? :: x
    end function use_array
end interface

我知道我必须要处理的空终止的问题了。
非常感谢。

I do know that I'll have to deal with the null-termination issue too. Many thanks.

推荐答案

我们做的是使用 C_PTR 阵列指向字符串的方式。例如:

The way we do it is to use a C_PTR array to point to strings. For example:

CHARACTER(LEN=100), DIMENSION(numStrings), TARGET :: stringArray
TYPE(C_PTR), DIMENSION(numStrings) :: stringPtrs

然后我们设定中的字符串字符串数组,记住空终止它们,例如:

then we set our strings in stringArray, remembering to null-terminate them such as:

DO ns = 1, numStrings
   stringArray(ns) = "My String"//C_NULL_CHAR
   stringPtrs(ns) = C_LOC(stringArray(ns))
END DO

stringPtrs 传递给C函数。

C函数有接口:

void stringFunc(int *numStrings, char **stringArray) {
    int i;
    for(i=0;i<*numStrings;++i) {
       printf("%s\n",stringArray[i]);
    }
 }

这篇关于用FORTRAN ISO_C_BINDING-C桥梁字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆