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
相关推荐
WJ.Polar15 小时前
Java封装、继承、多态
java·开发语言
摇滚侠15 小时前
Java 中如何表示负数,有符号和无符号的区别,补码的计算规则,char byte short int long 的范围
java·开发语言
weixin_3077791315 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
爱读书的小胖15 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
鸽鸽程序猿15 小时前
【项目】【在线判题系统】b端题目增删改
开发语言·python
Lhappy嘻嘻15 小时前
读懂 JVM:内存模型、类加载机制、分代回收
java·开发语言·jvm
Code_Solitude16 小时前
c语言:关于qsoet函数知识点
c语言·数据结构·算法
weixin_3077791316 小时前
C++代码实现MATLAB中的spectralcluster函数功能
开发语言·c++·算法·matlab
鸽鸽程序猿16 小时前
【项目】【在线判题系统】c端:竞赛报名
c语言·开发语言
Wang's Blog16 小时前
Java 项目实战: 交友项目 - 个人资料管理的需求分析与接口设计
java·开发语言·交友