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
相关推荐
火星数据-Tina1 天前
Python + WebSocket 实现实时体育比分系统(含数据库设计与前端演示)
开发语言·前端
⑩-1 天前
浅学Java-设计模式
java·开发语言·设计模式
攻心的子乐1 天前
软考 关于23种设计模式
java·开发语言·设计模式
qq_479875431 天前
C++ ODR
java·开发语言·c++
一叶之秋14121 天前
Qt开发初识
开发语言·qt
ANGLAL1 天前
25.Spring Boot 启动流程深度解析:从run()到自动配置
java·开发语言·面试
Momentary_SixthSense1 天前
serde
开发语言·rust·json
MediaTea1 天前
Python 文件操作:JSON 格式
开发语言·windows·python·json
2501_930707781 天前
使用C#代码添加或删除PPT页面
开发语言·c#·powerpoint
百锦再1 天前
金仓数据库提出“三低一平”的迁移理念
开发语言·数据库·后端·python·rust·eclipse·pygame