用于调用返回指针的 C 函数的 Fortran 接口 [英] Fortran interface to call a C function that return a pointer

查看:18
本文介绍了用于调用返回指针的 C 函数的 Fortran 接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C 函数,

double* foofunc() 
{
  /* Function Body */
}

我不知道如何在Fortran中声明一个接口来调用这个C函数.

I don't know how to declare an interface in Fortran to call this C function.

另外,如果一个指针应该指向 GPU 设备内存,我如何在 Fortran 接口中定义它?我需要使用 DEVICE 属性吗?

Also if a pointer is supposed to be pointing to GPU device memory, how could I define that in the Fortran interface? Do I need to use DEVICE attribute.

请使用 Fortran 直到 2003 年支持的功能.

Please use features supported by Fortran up to 2003.

有什么建议吗?

推荐答案

既然你有 Fortran 2003,连接 Fortran 和 C 的简单方法是使用 ISO C 绑定.(大多数 Fortran 95 编译器现在都支持 ISO C 绑定,即使它们不是完整的 Fortran 2003 编译器.)这比早期答案中建议的复杂方法要好得多,这在早期是必要的——它是语言的一部分,因此是可移植的,并且独立于编译器和平台.但是 Fortran 2003 版本并没有涵盖任何可能性.(下一个 Fortran 将添加与 C 接口的其他情况.)您可以轻松地传递一个作为 C 指针的参数——只需在 Fortran 声明中省略值"属性即可.指向指针的指针需要 C_PTR.我不知道将指针作为函数返回...有时间我将不得不进行实验.如果必须,制作一个简单的 C 粘合例程,将函数返回的指针转换为参数——这种情况很简单.

Since you have Fortran 2003, the easy way to interface Fortran and C is to use the ISO C Binding. (Most Fortran 95 compilers now support the ISO C Binding, even if they aren't full Fortran 2003 compilers.) This is far, far better than the complicated methods suggested in an earlier answer, which were necessary in an earlier era -- it is part of the language and therefore portable, and compiler and platform independent. But the Fortran 2003 version doesn't cover ever possibility. (The next Fortran will add additional cases of interfacing to C.) You can easily pass an argument that is a C pointer -- just leave off the "value" atttribute in the Fortran declaration. A pointer to a pointer needs C_PTR. I don't know about a pointer as a function return... I will have to experiment when I have time. If you have to, make a trivial C glue routine that converts the pointer of the function return into an argument -- that case is easy.

是指向 GPU 设备内存的指针——除非您的编译器具有非标准功能,否则它不会有DEVICE".也许易变"会有所帮助?创建适当的用户定义类型...

Re a pointer to GPU device memory -- unless your compiler has a non-standard feature, it won't have "DEVICE". Perhaps "volatile" will help? Create an appropriate user-defined type...

gfortran 手册中的与 C 的互操作性"下有示例.由于这是语言的一部分,即使您不使用 gfortran,本文档也应该有所帮助.

There are examples in the gfortran manual under "Interoperability with C". Since this is part of the language, this documentation should help even if you aren't using gfortran.

这篇关于用于调用返回指针的 C 函数的 Fortran 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆