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
相关推荐
小樱花的樱花几秒前
Linux 线程的创建
linux·c语言·开发语言
xiaoshuaishuai820 分钟前
C# AI实现PR处理、单元测试
开发语言·c#·log4j
C++、Java和Python的菜鸟20 分钟前
第7章 Java高级技术
java·开发语言
LONGZHIQIN22 分钟前
C#基础复习笔记
开发语言·笔记·c#
可靠的仙人掌37 分钟前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php
学逆向的1 小时前
汇编——数据存储模式
开发语言·汇编·网络安全
geovindu1 小时前
CSharp: Prototype Pattern
开发语言·后端·设计模式·.net·原型模式·创建型模式
天天进步20152 小时前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
aaPIXa6222 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
eybk2 小时前
写一个可以编制pdf文件的python程序
开发语言·python·pdf