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 小时前
函数:编程中的核心概念
开发语言·前端·javascript
阿米亚波2 小时前
【C++】流式数据输入处理(不完全整理)
开发语言·c++·笔记
大模型码小白3 小时前
JAVA 集合框架进阶:List 与 Set 的深度解析与实战
java·开发语言·人工智能·windows·语言模型·list·ai编程
皓月斯语4 小时前
【C++基础】三目运算符
开发语言·数据结构·c++
初願致夕霞4 小时前
C++懒汉单例设计详解
服务器·开发语言·c++
脱胎换骨-军哥4 小时前
C++分布式系统设计:从通信引擎到分布式共识
开发语言·c++·分布式
Discipline~Hai5 小时前
ARM01-ARM体系架构
linux·c语言·arm开发·架构
脱胎换骨-军哥5 小时前
C++零成本抽象理论深度拆解:现代C++如何在不牺牲性能的前提下提供高级语法封装
java·开发语言·c++
lbb 小魔仙5 小时前
VS Code Python 高级调试技巧:从入门到精通
开发语言·python
方便面不加香菜6 小时前
C++ 模板进阶
开发语言·c++