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
相关推荐
sel_921 分钟前
【强化学习】Hands-on Modern RL项目实践|OPD 算法完整解析
人工智能·深度学习·算法·机器学习·语言模型
ly768942 分钟前
JavaScript 从入门到进阶:核心语法、异步编程与工程化实践
开发语言·javascript·ecmascript
Navigator_Z1 小时前
LeetCode //C - 1209. Remove All Adjacent Duplicates in String II
c语言·算法·leetcode
落魄大学生之流水线上谋生计1 小时前
Java锁全面指南:从基础概念到企业级应用
java·开发语言
for_ever_love__1 小时前
python基础语法学习: 闭包
开发语言·python·学习·闭包
ly76891 小时前
Python 全面入门:从核心语法到工程实践
开发语言·python
艾伦_耶格宇2 小时前
【AI】-4 OpenCode Go 接入 Obsidian 完整指南
运维·开发语言·人工智能·agent·opencode
旋生万物3 小时前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf
ShineWinsu3 小时前
对于 C++:C++14中从变量模板、泛型 Lambda 到并发与字面量的解析
c++·算法