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
相关推荐
我爱写代码?几秒前
Spark 集群配置、启动与监控指南
大数据·开发语言·jvm·spark·mapreduce
买了一束花4 分钟前
数据预处理之数据平滑处理详解
开发语言·人工智能·算法·matlab
秭霏鱼5 分钟前
Python+大模型 day01
开发语言·python
破晓的历程7 分钟前
Qt之Qfile类
开发语言·qt
纸包鱼最好吃28 分钟前
java基础-package关键字、MVC、import关键字
java·开发语言·mvc
njsgcs28 分钟前
opencascade.js stp vite webpack 调试笔记
开发语言·前端·javascript
在右ZR30 分钟前
嵌入式(c语言篇)Day9
c语言
PgSheep34 分钟前
Spring Cloud Gateway 聚合 Swagger 文档:一站式API管理解决方案
java·开发语言
林鸿群37 分钟前
go语言实现IP归属地查询
开发语言·golang·ip归属地
学地理的小胖砸1 小时前
【Python 异常处理】
开发语言·python