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
相关推荐
鱼子星_13 分钟前
【数据结构】排序的拓展——快速排序的生态多样性与归并排序沾染文件操作
c语言·数据结构·算法
javajenius13 分钟前
Pixi:用 Rust 重写 Conda 体验的包管理工具
开发语言·其他·rust·conda
神明不懂浪漫14 分钟前
【第二章】Java中的数据类型,运算符与程序逻辑控制
java·开发语言·经验分享·笔记
laowangpython14 分钟前
tokio-rstracing:Rust 可观测性的标准答案
开发语言·后端·其他·rust
傻啦嘿哟20 分钟前
为什么Python没有块级作用域?
开发语言·python
技术小结-李爽30 分钟前
【工具】Shell之Bash、Zsh配置文件的使用
开发语言·bash
壮Sir不壮41 分钟前
GO语言——GMP调度模型
linux·开发语言·golang·go·操作系统·线程·协程
枫叶丹442 分钟前
【HarmonyOS 6.0】MDM Kit 深度解析:企业级 user_grant 权限集中管理策略
开发语言·华为·harmonyos
鱼子星_43 分钟前
C++从零开始系列篇(一):C++入门——命名空间,输入输出与缺省参数
开发语言·c++
就叫_这个吧1 小时前
Java使用tomcat+servlet+filter实现简单的登录功能,需先登录再进行页面数据管理操作
java·开发语言·servlet·tomcat·jsp·filter