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
相关推荐
杜 硕2 分钟前
从零开始的C++生活——第十五讲
开发语言·数据结构·c++·生活
sunly_8 分钟前
Go 切片详解
开发语言·oracle·golang
fengkai454522 分钟前
Python对接LangChain智能体开发(Tool工具调用与 Agent智能体)
运维·开发语言·python·langchain·llm·ai agent·tool
随流寻影1 小时前
利用 C++ 实现二叉搜索树的增删查
开发语言·c++
总要学点什么2 小时前
第128篇:镜头光晕与高光——把逆光太阳晕成会躲山的光斑
开发语言·javascript·数码相机·microsoft·材质·cesium
Escalating_xu2 小时前
【COZE实战】插件与知识库(三):让智能体会查资料,也会使用工具
开发语言·网络·人工智能·ai
学逆向的2 小时前
C++多态 汇编分析
开发语言·汇编·c++·网络安全
阿凤212 小时前
学习java---流程控制篇
java·开发语言·学习
derek19973 小时前
软考软件设计师:白盒覆盖哪条最弱、McCabe 复杂度怎么数、单元测试最能发现什么错
c语言·c++·计算机网络·软件工程·学习方法
Code_Solitude3 小时前
c语言:期末最后一道大题模拟
c语言·开发语言