alloc complex data in c, and access in fortran

a.f90

bash 复制代码
program main
        use iso_c_binding
        implicit none
        type(c_ptr) :: ADD1
        type(c_ptr) :: c_ptr1
        external ADD1
        integer :: i
        complex :: z
        complex, pointer :: S(:)

        c_ptr1 = ADD1( )

        call c_f_pointer(c_ptr1, S, [10])
        print *, 'Array from C function: '
        do i = 1, 5
        print *, S(i)
        end do
        !        z = (1.0, 7.0)  ! 0 is the real part, 5.0 is the imaginary part
        !        print *, 'Complex number: ', z
end program

b.c

bash 复制代码
# include <stdlib.h>
# include <stdio.h>

float* add1_( )
{
        int n = 10; // size of the array
        float *arr = (float *)malloc(n * sizeof(float)); // 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("%f ", arr[i]); // Print each element
        }
        printf("\n");
        return (float *) arr;
}

Makefile

bash 复制代码
all:
        gcc -c b.c -O0 -g
        gfortran a.f90 b.o -O0 -g -o a.out
相关推荐
折哥的程序人生 · 物流技术专研4 分钟前
AI 编程与行业赋能|专栏总目录(持续更新)
开发语言·人工智能·软件工程·ai编程
SilentSamsara7 分钟前
爬虫工程化:Playwright + 反反爬 + 数据清洗管道实战
开发语言·爬虫·python·青少年编程·playwright
AI玫瑰助手10 分钟前
Python函数:函数的返回值(return)与多值返回
开发语言·python·信息可视化
花果山~~程序猿12 分钟前
快速认识python项目的虚拟环境
开发语言·python
basketball61619 分钟前
Go语言从入门到进阶:8. 接口
开发语言·后端·golang
gCode Teacher 格码致知20 分钟前
Python教学:字符编码的四种环境-由Deepseek产生
开发语言·python
铁链鞭策大师23 分钟前
JavaEE之多线程
java·开发语言·java-ee
我是唐青枫27 分钟前
Java Optional 实战指南:优雅处理空值与链式转换
java·开发语言
basketball61639 分钟前
设计模式入门:2. 工厂模式详解 C++实现
开发语言·c++·设计模式
Lumbrologist39 分钟前
【C++】零基础入门 · 第 16 节:智能指针
开发语言·c++