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
相关推荐
布莱克6052 小时前
Swift 可选链详解:从语法到实战
开发语言·ios·swift·可选链
布莱克6052 小时前
Swift 类型转换详解:从基础语法到实战技巧
开发语言·ios·swift·类型转换
码途行者2 小时前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang
艾莉丝努力练剑3 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
Evand J4 小时前
【MATLAB例程,无人机避障7】基于RRT*与人工势场法(RRT*+APF)的多无人机二维动态路径规划与避障。附下载链接
开发语言·matlab·无人机·rtt·路径规划·人工势场
布莱克6054 小时前
Objective-C 基本语法详解:从零开始掌握 iOS 开发语言
开发语言·ios·objective-c·基础·语法
码途行者4 小时前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
Navigator_Z5 小时前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
CoderYanger5 小时前
Java EE 进阶:14.案例综合练习-博客系统(第三弹) :用户登录+强制登录
java·服务器·开发语言·数据库·spring boot·java-ee·mybatis
CoderYanger11 小时前
Java EE 进阶:13. Spring事务和事务传播机制(第二弹)
java·开发语言·数据库·spring boot·后端·spring·java-ee