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
相关推荐
牛奔4 小时前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
2601_951644324 小时前
C语言二级备考指南
c语言·编程基础·编译环境·二级考试·题库选择
geovindu4 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
学逆向的4 小时前
汇编——JCC指令
开发语言·汇编·网络安全
mayaairi5 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
kite01216 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
l156469487 小时前
突围!图文混合知识库难以解析,Kimi-K3 原生视觉架构深耕知识工作,DMXAPI 统一接口,缩短项目开发周期
java·大数据·开发语言
charlie1145141917 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
日拱一卒——功不唐捐8 小时前
红黑树删除(C语言)
c语言·数据结构
IT小盘9 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python