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
相关推荐
你怎么知道我是队长3 分钟前
JavaScript 的控制语句介绍
开发语言·javascript·ecmascript
RSTJ_162526 分钟前
PYTHON+AI LLM DAY ONE HUNDRED AND THREE
开发语言·人工智能·python
charlie1145141911 小时前
RK3506B: buildroot:出一份正规的最小 rootfs
开发语言·嵌入式·开源项目·rk3506b
Byron Loong2 小时前
【c#】Bitmap释放之 大象与蚊子
开发语言·c#
音符犹如代码2 小时前
Java动态线程池:避坑原生线程池,吃透Dynamic-TP,手写一个Demo
java·开发语言
喜欢就别2 小时前
平均风险:Rényi DP 和零集中 DP
开发语言·r语言
无足鸟ICT3 小时前
【RHCA+】bash命令
linux·开发语言·bash
光芒Shine3 小时前
【C语言-记录点】
c语言
方华世界3 小时前
企业级Java AI Agent应用平台
java·开发语言·人工智能
ujainu小4 小时前
原生性能优化:6变量实现高效桥接
开发语言·华为·性能优化·harmonyos