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
相关推荐
轻舟技术A6 小时前
Pi 的 Rust 实现来了:rpi,不止一个终端 Agent
开发语言·后端·rust
C++ 老炮儿的技术栈6 小时前
static的作用
c语言·c++·人工智能·单片机·c
额额额对了6 小时前
嵌入式 Linux 启动程序文件
开发语言·嵌入式硬件·php
子非鱼a6 小时前
【WEB】EasySSTI
java·开发语言·前端
奈葵6 小时前
Python
开发语言·python
Nebula_g6 小时前
JavaSE项目实践:红包雨-线程池/线程
java·开发语言
外收内放6 小时前
Python基础语法练习题(56优化版补充)
开发语言·python
小羊没烦恼!6 小时前
jQuery1.5的改进细节
java·服务器·开发语言·前端·c#
程序员老陆7 小时前
C++ 未定义行为全景:对象模型、优化边界与工程防御
开发语言·c++·程序设计