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
相关推荐
Data_Journal1 小时前
用于网页抓取的 Node-unblocker
大数据·开发语言·数据库·python·scrapy
豆角焖肉1 小时前
SSM 聚合项目搭建:多 Maven 模块项目
开发语言·python·pycharm
Frank_refuel1 小时前
【C++八股】面向对象
开发语言·c++
m0_380743873 小时前
为 OpenAI 兼容接口配置教程
开发语言·python·node.js
M78佐菲3 小时前
c语言学习笔记:排序与查找方法整理
linux·c语言·笔记·学习·算法
万邦科技Lafite3 小时前
阿里巴巴拍立淘按图搜索商品API返回值实践:提升用户购物满意度的关键措施
开发语言·api·开放api·电商开放平台·京东开放平台
小小龙学IT4 小时前
Qt 6 跨平台开发完全指南:从信号槽机制到实际项目落地
开发语言·qt
leisoo80974 小时前
ig50数据落盘ClickHousevsTimescaleDBvsDuckDB实测对比 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·json
wWYy.4 小时前
C++与C的区别
c语言·c++
敢敢のwings5 小时前
智元 GO-2 与 AgiBot-World 深度解读
开发语言·后端·golang