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
相关推荐
oioihoii19 分钟前
现代C++:一场静默的革命,告别“C with Classes”
c语言·jvm·c++
Jonathan Star1 小时前
JavaScript 中,原型链的**最顶端(终极原型)只有一个——`Object.prototype`
开发语言·javascript·原型模式
普通网友1 小时前
C++中的组合模式
开发语言·c++·算法
q***61501 小时前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php
Dneccc1 小时前
Qt5配置MSVC2017
开发语言·qt
江公望1 小时前
Qt QByteArray类型,10分钟讲清楚
开发语言·c++·qt
小灰灰搞电子1 小时前
Qt Sensors 传感器框架详解
开发语言·qt
LNN20221 小时前
Qt 5.8 中的 Qt Test:轻松实现自动化测试
开发语言·qt
2501_941111461 小时前
C++中的组合模式变体
开发语言·c++·算法
啵啵鱼爱吃小猫咪1 小时前
机器人具身智能汇总
开发语言