gpt4 book ai didi

将复杂的 c 函数转换为 fortran

转载 作者:行者123 更新时间:2023-11-30 16:37:55 24 4
gpt4 key购买 nike

我正在将一些 C 函数转换为 Fortran。在我的 c 例程中,有两个如下所示的结构定义

typedef struct heapnode {
double c;
int n;
} heapnode;

typedef struct heap {
int n;
int sz;
heapnode *d;
} heap;

我将上述两种类型定义转换为 Fortran,如下所示,效果很好。

type heapnode

real*8 :: c
integer*4 :: n

endtype heapnode


type heap

integer*4 :: n
integer*4 :: sz
type(heapnode), pointer :: d

endtype heap

我的问题是关于上述两个结构的启动。这里的要求是我们应该有一个堆类型变量,并且在该堆类型变量中我们应该有多个堆节点。

为了演示这一点,我在下面展示了打印堆元素的 C 代码

int i;

FILE *f = stdout;
fprintf(f, "Printing heap\n");

for (i=0; i<h->n; i++) {
fprintf(f, "[%4d]: n = %5d, c = %17.12lg\n", i, h->d[i].n, h->d[i].c);
}

上面代码中的h是堆类型变量h->n 是堆变量 h 中的堆节点数

这里我们可以看到访问堆节点变量为 h->d[i]

我展示了创建此堆变量和下面节点的 C 代码

 void *vspace, *oldvspace;

heap *h /* heap */
heapnode *d; /* heap node */


h->n = 0;
h->sz = 8;

oldvspace = (void *) h;
vspace = (void *)(h + 1); / * address of next node */

d = (heapnode *)vspace; / *point heapnode to above address */
h->d = d; / *assign heapnode to new node */

上面我们可以看到,在特定的内存位置创建一个变量(这次是堆节点),并将一个指针变量指向该变量。

我想知道,我们如何使用 Fortran 来做到这一点。您能否给我一些提示来做到这一点。

最佳答案

标准 Fortran 中不提供指针算术。然而,编译器中有一个非标准扩展,称为“Cray 指针”,它将允许有限的指针算术。请注意,Cray 指针算术与 C 风格指针算术不同 - 使用 Cray 指针递增指向派生类型的指针不会产生等于原始内存位置加上存储派生类型所需字节数的指针值。因此,像 vspace = (void *)(h + 1); 这样的语句无法准确模拟。如果您希望代码可移植,那么我不推荐使用 Cray 指针。

关于将复杂的 c 函数转换为 fortran,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47706914/

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