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
相关推荐
库克克8 小时前
【C++】类和对象--类对象模型与大小计算
开发语言·jvm·c++
布朗克1688 小时前
Go 入门到精通-15-错误处理
开发语言·python·golang·错误处理
zzb15808 小时前
Zed 配置 Swift / iOS 开发
开发语言·ios·swift
北冥you鱼10 小时前
Go-Ethereum (Geth) 最佳实践:从部署到生产环境优化
开发语言·后端·golang
这不小天嘛17 小时前
JAVA八股——J集合篇
java·开发语言
AOwhisky17 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
ysu_031418 小时前
06 | 200个单元测试C项目也能TDD
c语言·单元测试·tdd
喜欢的名字被抢了20 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi
从零开始的代码生活_1 天前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
wabs6661 天前
关于单调栈【力扣739.每日温度的思考】
java·开发语言