使用SWIG从Fortran源代码创建Python模块
Creating a Python module from Fortran source code using SWIG
我正在从事一个项目,该项目涉及为用Fortran编写的程序创建Python接口。我做了一些研究并决定使用SWIG,首先向C++公开Fortran例程,然后用SWIG封装它们。但是,我很难让Python模块正常工作。
举个例子,我有一个Fortran函数:
function sum_array(input_array, length) result(sum)
implicit none
integer, value, intent(in) :: length
real(kind=8), intent(in), dimension(length) :: input_array
real(kind=8) :: sum
integer :: i
sum = 0.0
do i=1, length
sum = sum + input_array(i)
end do
end function sum_array
带有C声明:
double sum_array(double* input_array, int length);
我使用的SWIG接口文件是:
%module sum_array
%{
#define SWIG_FILE_WITH_INIT
#include "sum_array.h"
%}
%include "numpy.i"
%init %{
import_array();
%}
%apply (double* IN_ARRAY1, int DIM1) {(double* input_array, int length)};
%include "sum_array.h"
此接口文件使用numpy.i接口。
我正在将这段代码(使用make)编译成一个共享对象,如下所示:
$ swig -python -c++ -o sum_array_wrap.cpp sum_array.i
$ gfortran -c sum_array.f90 -o sum_array.o -fpic -fno-underscoring
$ gcc -I/usr/include/python2.7 -c sum_array_wrap.cpp -o sum_array_wrap.o -fpic -std=c++0x
$ gfortran sum_array_wrap.o sum_array.o -o _sum_array.so -shared -Wl,-soname,_sum_array.so -lstdc++
当我尝试在Python中导入模块时,我会从:中得到"NameError:name‘sum_array’is not defined"
from numpy.random import rand
from _sum_array import *
input_array = rand(5)
sum = sum_array(input_array)
根据我从解释器中的help()获得的信息,我认为链接器没有在库中包含sum_array函数,我认为这就是问题所在。
关于如何让它发挥作用,有什么想法吗?
顺便说一句,关于其他工具而不是SWIG的建议非常受欢迎,因为这是我第一次这样做,也是我尝试过的唯一方法。
这一次的问题是名称篡改。fortran sompiler不使用它,因此导出符号名称为sym_array
,但稍后您使用C++编译接口,因此链接器希望看到类似_Z9sum_arrayPdi
的内容。解决方案是将标头内容包装到中
#ifdef __cplusplus
extern "C" {
#endif
double sum_array(double* input_array, int length);
#ifdef __cplusplus
}
#endif
相关文章:
- 我想通过带有C++和Python的插件创建一个可扩展的应用程序
- C++套接字客户端到 Python 服务器未创建连接
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针
- 在 c++ 中创建一个类似 python 的列表
- 如何创建和使用存储为 c++ 对象的 python 对象?
- 从C++获得对在python中创建的C++类的访问权限
- 在c++中从包含新操作的python中创建的pb图创建图
- 如何为Python Swigged C++对象创建和分配回调函数
- 如何创建一个接口,允许我访问C++中的按钮(和其他ui)函数,该函数是使用python中的MFC实现的
- Windows错误:异常:使用从C++到Python的ctypes创建DLL时出现访问冲突或Windows错误193
- 在C++中创建 python "列表"
- 如何在 python 交易模型中创建功能时间条件
- 如何在python中创建等效的结构并使用malloc更改空指针的引用
- 从C 内部在本地范围中创建Python对象
- 使用 boost::p ython 从C++创建 python collections.namedtuple
- 使用SWIG从Fortran源代码创建Python模块
- 在c#、c++和java中创建python弱类型结构的强类型版本
- 创建Python构造函数,参数来自c++, PyObject
- 如何从C++创建Python Decimal对象
- 是否可以在C++程序中创建Python模块中定义的类的实例