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
相关推荐
Maybe_ch14 分钟前
Blazor-<select>
开发语言·c#·blazor
华梦岚2 小时前
F#语言的学习路线
开发语言·后端·golang
lly2024063 小时前
XML 元素:结构化数据的基石
开发语言
钟离墨笺3 小时前
【c++】四种类型转换形式
开发语言·c++
“抚琴”的人3 小时前
【C#零基础从入门到精通】(一)——了解C#
开发语言·c#
梅清瑶3 小时前
Powershell语言的数据库编程
开发语言·后端·golang
吴天德少侠3 小时前
设计模式中的关联和依赖区别
java·开发语言·设计模式
汤姆和杰瑞在瑞士吃糯米粑粑3 小时前
【C++学习篇】C++11
开发语言·c++
zjkzjk77113 小时前
C++ 左值引用 & 右值引用 && std::move()左值改右值 移动构造函数()
开发语言·c++
Thomas_YXQ3 小时前
Unity3D Shader 简析:变体与缓存详解
开发语言·前端·缓存·unity3d·shader