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
相关推荐
心疼你的一切13 分钟前
三菱FX5U PLC与C#通信开发指南
开发语言·单片机·c#
Tim_1024 分钟前
【C++入门】04、C++浮点型
开发语言·c++
@淡 定30 分钟前
Java内存模型(JMM)详解
java·开发语言
谈笑也风生31 分钟前
经典算法题型之复数乘法(二)
开发语言·python·算法
hkNaruto33 分钟前
【C++】记录一次C++程序编译缓慢原因分析——滥用stdafx.h公共头文件
开发语言·c++
先知后行。1 小时前
python的类
开发语言·python
派大鑫wink1 小时前
【Day12】String 类详解:不可变性、常用方法与字符串拼接优化
java·开发语言
JIngJaneIL1 小时前
基于springboot + vue健康管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
dyxal1 小时前
Python包导入终极指南:子文件如何成功调用父目录模块
开发语言·python
我居然是兔子1 小时前
Java虚拟机(JVM)内存模型与垃圾回收全解析
java·开发语言·jvm