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
相关推荐
Fish41743 小时前
《C语言程序设计》琐碎知识点总结笔记
c语言·命令行参数·c语言程序设计·变量存储类型·函数存储类型·编译预处理
长安第一美人5 小时前
C 语言可变参数(...)实战:从 logger_print 到通用日志函数
c语言·开发语言·嵌入式硬件·日志·工业应用开发
Larry_Yanan5 小时前
Qt多进程(一)进程间通信概括
开发语言·c++·qt·学习
superman超哥5 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
不爱吃糖的程序媛5 小时前
Ascend C开发工具包(asc-devkit)技术解读
c语言·开发语言
bu_shuo5 小时前
MATLAB奔溃记录
开发语言·matlab
Learner__Q6 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
你的冰西瓜6 小时前
C++标准模板库(STL)全面解析
开发语言·c++·stl
阿昭L6 小时前
leetcode链表相交
算法·leetcode·链表
闻缺陷则喜何志丹6 小时前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何