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
相关推荐
LYS_06184 分钟前
寒假学习(2)(C语言2+模数电2)
c语言·学习·算法
json{shen:"jing"}5 分钟前
10_自定义事件组件交互
开发语言·前端·javascript
一位搞嵌入式的 genius8 分钟前
深入理解 JavaScript 异步编程:从 Event Loop 到 Promise
开发语言·前端·javascript
brevity_souls13 分钟前
SQL Server 窗口函数简介
开发语言·javascript·数据库
火云洞红孩儿23 分钟前
零基础:100个小案例玩转Python软件开发!第六节:英语教学软件
开发语言·python
AI殉道师35 分钟前
FastScheduler:让 Python 定时任务变得优雅简单
开发语言·python
花间相见43 分钟前
【JAVA开发】—— HTTP常见请求方法
java·开发语言·http
楼田莉子1 小时前
Linux系统小项目——“主从设计模式”进程池
linux·服务器·开发语言·c++·vscode·学习
走粥1 小时前
选项式API与组合式API的区别
开发语言·前端·javascript·vue.js·前端框架
从此不归路1 小时前
Qt5 进阶【7】网络请求与 REST API 实战:QNetworkAccessManager 深度应用
开发语言·c++·qt