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
相关推荐
编码浪子11 分钟前
趣味学RUST基础篇(构建一个命令行程序2重构)
开发语言·重构·rust
echoarts1 小时前
MATLAB R2025a安装配置及使用教程(超详细保姆级教程)
开发语言·其他·matlab
阿方.9181 小时前
《数据结构全解析:栈(数组实现)》
java·开发语言·数据结构
CYRUS_STUDIO1 小时前
LLVM 不止能编译!自定义 Pass + 定制 clang 实现函数名加密
c语言·c++·llvm
CYRUS_STUDIO1 小时前
OLLVM 移植 LLVM 18 实战,轻松实现 C&C++ 代码混淆
c语言·c++·llvm
Dovis(誓平步青云)1 小时前
《探索C++11:现代语法的内存管理优化“性能指针”(下篇)》
开发语言·jvm·c++
南山十一少2 小时前
STM32CubeMX + HAL 库:基于 I²C 通信的 BMP280气压海拔测量
c语言·stm32·嵌入式硬件
charlie1145141912 小时前
前端三件套简单学习:HTML篇1
开发语言·前端·学习·html
kebeiovo2 小时前
项目必备流程图,类图,E-R图实例速通
开发语言·r语言·流程图
软件开发-NETKF88882 小时前
JSP到Tomcat特详细教程
java·开发语言·tomcat·jsp·项目运行