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
相关推荐
1-1=011 分钟前
C# 委托与事件
开发语言·c#
Fuyo_111924 分钟前
C++ 运行时多态与虚函数机制全面剖析【面试重点】
开发语言·c++·面试
§ꦿCFོ༉34 分钟前
嵌入式八股—C语言入门学习(一)
c语言·编程语言·嵌入式八股文
w_zero_one1 小时前
递归算法(一)
java·开发语言·算法
Julien20042 小时前
管理机密(一)
运维·服务器·开发语言·学习方法
Chen_harmony2 小时前
七、STL与string类
开发语言·c++
沐晓时光2 小时前
C语言入门,字符串和字符串函数知识讲解
c语言·开发语言
xxxiugou1233 小时前
C++命名空间与引用全解析
开发语言·c++
yangmu32034 小时前
编程语言发展简史:从机器指令到智能协作
开发语言
Pniubi7 小时前
Java为什么要分堆和栈
java·开发语言