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
相关推荐
Logic1011 分钟前
C语言/数据结构位运算题解:异或XOR找出独特卡片数字——只出现一次的元素
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
郝学胜-神的一滴6 分钟前
C++20模板元编程 02:吃透模板基础核心四大核心知识点
开发语言·数据结构·c++·程序人生·软件工程·visual studio
troy12812 分钟前
Visual Studio Code 详细教程:从入门到高效开发
开发语言·python
泡海椒21 分钟前
jquick-pdf 超详细入门教程:Java 轻量级 HTML 模板生成 PDF 工具
java·开发语言
八年。。26 分钟前
WSL学习(三)——搭建Linux + C++ + SOME/IP 基础开发环境
开发语言·笔记·ubuntu
代码王同学27 分钟前
2026.9.15日C++类和对象学习收获笔记
c语言·c++
孙启超32 分钟前
【AI开发之Rust】第 6 课:结构体、枚举与方法 —— 开始定义自己的类型
开发语言·人工智能·后端·ai·rust
irislinAmelia40 分钟前
Day11文章_多路视频流加权公平调度与令牌桶QoS
c语言·人工智能
电商API_1800790524743 分钟前
电商平台数据分析实战_帖子
开发语言·爬虫·python·数据采集·京东
传奇开心果编程1 小时前
【Rust入门知识点学与练】第36课:所有权——移动、借用、Copy、切片
开发语言·学习·rust