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
相关推荐
踏着七彩祥云的小丑几秒前
Go学习第3天:变量+常量+运算符
开发语言·学习·golang·go
专注搞钱几秒前
用Python写了个SPC自动分析工具,效率提升10倍
开发语言·python
码云骑士4 分钟前
【3.Java基础】Java运算符详解:从算数运算到逻辑判断,一篇文章全部掌握
java·开发语言
雪落漂泊6 分钟前
C++ 继承与多态(下)
开发语言·c++
川冰ICE7 分钟前
JavaScript工程化②|Webpack5基础配置,打包你的第一个项目
开发语言·javascript·ecmascript
YHHLAI7 分钟前
JavaScript 同步异步精讲:单线程、事件循环、Promise 执行机制
开发语言·javascript·ecmascript
yijianace7 分钟前
Python爬虫实战:ThreadPoolExecutor多线程采集书籍信息与图片下载
开发语言·爬虫·python
资深流水灯工程师8 分钟前
PySide6 + Qt Designer + PyCharm 完整开发流程
开发语言·qt·pycharm
BAGAE9 分钟前
FEC-RS前向纠错编码理论及工程实施研究
c语言·c++·qt·算法·决策树·链表
阿旭超级学得完10 分钟前
Linux基础指令 四(apt,vim,git,cgdb)
linux·服务器·开发语言·数据结构·c++·git·vim