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
相关推荐
把csdn当日记本的菜鸡1 分钟前
js查缺补漏
开发语言·javascript·ecmascript
lkbhua莱克瓦244 分钟前
Java练习——数组练习
java·开发语言·笔记·github·学习方法
武子康18 分钟前
Java-168 Neo4j CQL 实战:WHERE、DELETE/DETACH、SET、排序与分页
java·开发语言·数据库·python·sql·nosql·neo4j
通往曙光的路上30 分钟前
SpringIOC-注解
java·开发语言
闲人编程31 分钟前
Python与大数据:使用PySpark处理海量数据
大数据·开发语言·分布式·python·spark·codecapsule·大规模
T.Ree.44 分钟前
汇编_读写内存
开发语言·汇编·c#
oioihoii1 小时前
C/C++混合项目中的头文件管理:.h与.hpp的分工与协作
java·c语言·c++
kaikaile19951 小时前
基于MATLAB的直接序列扩频(DSSS)通信系统仿真实现
开发语言·matlab
czhc11400756631 小时前
C#1114 枚举
开发语言·c#
彷徨而立1 小时前
【C/C++】不能在派生类的构造函数初始化列表中直接初始化属于基类的成员变量
c语言·c++