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
相关推荐
海绵宝宝转agent几秒前
LeetCode100 LRU缓存思路讲解
java·开发语言·缓存
山下梅子酒22511 分钟前
洛谷-入门-B2080
c语言
AC赳赳老秦23 分钟前
OpenClaw 与 FineBI 联动方案:公开数据自动采集与实时业务分析看板实践
大数据·开发语言·python·php·finebi·deepseek·openclaw
通信瓦工28 分钟前
OCP 冷却环境与冷却剂分配单元(CDU)子项目
java·开发语言
坤坤子吖1 小时前
Python基础语法学习:函数
开发语言·笔记·python·学习
言乐61 小时前
Python体现逻辑回归和决策树的区别
开发语言·python·算法·决策树·逻辑回归
LOVE️YOU1 小时前
Python 类与对象的核心逻辑:从 self、cls 到点号、括号与链式调用
开发语言·python
顶点多余1 小时前
C/C++常见面试题
开发语言·c++
(Charon)1 小时前
【C++面试】右值引用与移动语义:std::move到底做了什么
开发语言·c++
TheITSea1 小时前
JavaScript Web APIs
开发语言·前端·javascript