fortran access pointer returned from c

a.f90

bash 复制代码
program main
        use iso_c_binding
        implicit none
        type(c_ptr) :: ADD1
        integer R
        integer(C_INT), pointer :: S(:)  ! Declare a Fortran pointer for the array
        type(c_ptr) :: c_ptr1
        external ADD1
        integer :: i

        R = 8
        c_ptr1 = ADD1( R )

        call c_f_pointer(c_ptr1, S, [10])  ! Assume the size is 10
        print *, 'Array from C function: '
        do i = 1, 10
        print *, S(i)
        end do
end program

b.c

bash 复制代码
# include <stdlib.h>
# include <stdio.h>

int* add1_( pf )
        int *pf;
{

        printf("%d\n",*pf);
        int n = 10; // size of the array
        int *arr = (int *)malloc(n * sizeof(int)); // allocate memory for n integers

        // Check if memory allocation was successful
        if (arr == NULL) {
                printf("Memory allocation failed\n");
                return NULL; // Return error code
        }
        // Initialize and print the array
        for (int i = 0; i < n; i++) {
                arr[i] = i * i; // Assign some values
                printf("%d ", arr[i]); // Print each element
        }
        printf("\n");
        return (int *) arr;
}

Makefile

bash 复制代码
all:
        gcc -c b.c
        gfortran a.f90 b.o -o a.out
相关推荐
tryxr13 分钟前
Java 多线程标志位的使用
java·开发语言·volatile·内存可见性·标志位
APItesterCris25 分钟前
高并发场景下的挑战:1688 商品 API 的流量控制、缓存策略与异步处理方案
大数据·开发语言·数据库·缓存
yyy(十一月限定版)27 分钟前
c语言——栈和队列
java·开发语言·数据结构
feeday28 分钟前
Python 删除重复图片 优化版
开发语言·python
.格子衫.32 分钟前
JS原型链总结
开发语言·javascript·原型模式
麦麦鸡腿堡35 分钟前
Java_MySQL介绍
java·开发语言·mysql
于是我说35 分钟前
一份Python 面试常见问题清单 覆盖从初级到高级
开发语言·python·面试
shoubepatien35 分钟前
JavaWeb_Web基础
java·开发语言·前端·数据库·intellij-idea
吧啦蹦吧1 小时前
`org.springframework.util.ClassUtils#forName
开发语言·python
CC.GG1 小时前
【C++】红黑树
java·开发语言·c++