【发布时间】:2015-05-13 22:56:45
【问题描述】:
我已经为 python 编写了一个 C 扩展(使用 Python/C API),它使用 distutils 构建并且运行良好。现在我想在 C 代码中添加一些 Fortran 例程的包装器。我正在寻找的最终结果是一个调用 Fortran 函数的 C 函数的 python 函数。
这可能吗?我可以成功地从 Python 调用 C,从 C 调用 Fortran,但是我无法将这三者结合起来。有任何想法吗?谢谢!
已编辑 这是我想要的结构的更详细示例:
假设我有一个名为 fortranfunc.f90 的 Fortran 例程和一个名为 cfunc.c 的 C 代码,其格式如下:
#include <Python.h>
#include<numpy/arrayobject.h>
static PyObject *cfunc(PyObject *self, PyObject *args);
extern double fortranfunc_(double*);
static PyObject *cfunc(PyObject *self, PyObject *args)
{
/* a bunch of C code here to calculate the double x */
y = fortranfunc_(&x); //now call the fortran function
/* now finish up using the value of y returned by the fortran function */
}
static PyMethodDef cfunc_methods[] = {{"cfunc", cfunc, METH_VARARGS, NULL},{NULL}};
void initcfunc(void)
{
Py_InitModule("cfunc", cfunc_methods);
import_array();
}
我正在尝试使用类似这样的 setup.py 文件来构建它:
from distutils.core import setup, Extension
import numpy as np
module1 = Extension('cfunc', sources = ['cfunc.c'])
setup (name = 'cfunc',
version = '1.0',
include_dirs = [np.get_include()],
ext_modules = [module1])
但是我不知道如何处理对fortranfunc.f90的依赖。
我希望这是独立于平台的 - 如果这不可能,我会寻找另一种解决方案!感谢您迄今为止提出的所有建议。
【问题讨论】:
-
您可以为 Fortan 代码使用 C 包装器。不确定这两种语言是否兼容 ABI。我想这取决于目标平台。如果包装器只是以 1:1 的比例转发所有参数,这甚至可能不会生成实际代码。
-
是的,这是可能的(我以前做过)。正确的方法取决于您的编译器和操作系统。在编译 C 代码和 Fortran 代码时,您现在使用哪些编译器标志?
-
Fortran 和 C 的互操作性甚至在标准中。请参阅 fortran-iso-c 绑定...
-
你想要 C 放在中间有什么特别的原因吗?
-
@IgnacioVazquez-Abrams:问我?只是一个建议。但是,如果 ABI 允许,它可能只需要一个 C 头文件和一个适当的 Python/C-API 模块。我只是不确定。那时,我为 Pascal 准备了一些东西,它主要需要 C-header 中的函数来反转参数列表。但那是十多年前的事了。
标签: python c fortran fortran-iso-c-binding