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
相关推荐
逝水无殇23 分钟前
C# 枚举(Enum)详解
开发语言·后端·c#
nianniannnn35 分钟前
c++复习自存--标准模板库STL
开发语言·c++·windows
努力努力再努力wz44 分钟前
【高性能网络库与HTTP Server系列】:基于主从 Reactor 模型实现高性能 C++ 网络库与 HTTP Server
开发语言·网络·数据结构·数据库·c++·网络协议·http
什巳1 小时前
JAVA练习275-乘积最大子数组
java·开发语言·数据结构·算法
lang201509281 小时前
Apache POI Word(docx) 实战教程:从入门到精通表格合并、图片插入与文档合并
java·开发语言·word
鱼毓屿御2 小时前
Python 装饰器与函数调用机制(复习笔记 · 2026-07-07)
开发语言·python
浩瀚地学2 小时前
【Java基础复习】IO流(二)
java·开发语言·经验分享·笔记·学习
^yi2 小时前
【C++】内存管理
开发语言·c++
AC赳赳老秦2 小时前
采购专员自动化:OpenClaw 自动比价、生成询价单、跟踪供应商报价进度实战指南
开发语言·数据库·人工智能·python·自动化·github·openclaw
QiLinkOS2 小时前
QiLink OS的失败数据共享平台的运作模式是否适用于所有行业?
android·开发语言·人工智能·算法·重构·开源