将数组从fortran传递给c++函数

Passing an array from fortran to a C++ function

本文关键字:c++ 函数 数组 fortran      更新时间:2023-10-16

我有一个主程序在Fortran。我在Visual Studio 2010上使用英特尔Visual Fortran XE 2011。我想使用一个函数,这是编码在 c++ 。我正在使用的函数是获取几个数组(来自主要fortran程序的输入集)并使用它们来形成输出数组(将返回给主要fortran程序)。我已经采取了以下步骤:

1)我用Fortran主程序和模块创建了一个Fortran项目,并将其设置为"启动项目"。

2)我创建了一个类型为"静态库"的c++项目。

3)我添加了$(IFORT_COMPILERvv)compilerlibia32,在这里解释http://software.intel.com/en-us/articles/configuring-visual-studio-for-mixed-language-applications

c++静态库的构建没有问题。我得到的错误是关于fortran程序中real(8)变量的声明。

对于所有真实的(8)声明,我得到以下两个错误,即总共6个错误:

错误#5082:语法错误,当期望:::%FILL, TYPE字节字符类DOUBLE DOUBLECOMPLEX DOUBLEPRECISION…时发现'('

error #5082:语法错误,当期望:(*,;;[/= =>

]
下面是我使用的代码:

主Fortran程序:

Program Fort_call_C
use iso_c_binding
implicit none
interface 
   subroutine vec_sum_c(a,b,c) bind (C, name = "vec_sum_c")
      use iso_c_binding
      implicit none
      real(8) (c_double), intent (in), dimension (*) :: a,b
      real(8) (c_double), intent (out), dimension (*) :: c
   end subroutine get_filled_ar
end interface  
integer:: i
integer (c_int)::m
real(8)(c_double),dimension(:):: a, b, c
open(unit=10, file="input_arrays.txt",status="unknown")
read(10,*) m
allocate(a(m),b(m),c(m))
do i=1,m
   read(10,*)a(i),b(i)
end do
close(10)
call vec_sum_c(m,a,b,c)
do i=1,m
   print*, c(i)
end do
pause
end program

, c++函数是:

extern"C" void vec_sum_c(int *m, double *a, double *b, double *c){
    int mm = *m;
    for(int i=0;i<=m-1;i++){
        c[i]=a[i]+b[i];
     }
}
有谁能帮我解决这个问题吗?请让我知道,如果从fortran程序发送整个数组到c++例程的想法是安全的还是有问题的(最好避免)尝试?

您的Fortran语法错误。你喝了两次真酒。试着

REAL(C_DOUBLE), INTENT(IN), DIMENSION(*) :: a, b

等。

C_DOUBLE是一个命名常量。该处理器的值恰好是8。

:

  • 您缺少C函数的Fortran接口体中的参数m
  • 您更改了Fortran接口体中开始和结束语句之间的子程序的名称!
  • 你的c++ for循环小于等于m比较,应该是mm

以这种方式发送整个数组没有固有问题。

我只设法从C传递了一个变量的值函数转换为FORTRAN函数

我在这里粘贴了两个源文件即main.c和fortran.f您可以在microsoft visual studio 10中使用这两个文件。后按照http://software.intel.com/en-us/articles/configuring-visual-studio-for-mixed-language-applications页面的建议在visual studio中进行所有设置,您需要进行另一个更改;

  1. 进入C/c++静态库的项目属性;
  2. 转到C/c++
  3. 转到代码生成
  4. 设置运行库为多线程调试(/MTd)

现在可以构建程序....

c:

#include <stdio.h>
#include <malloc.h>
void testc(double **pa, double **p)
{
 double b;
 double *a, *c;
 int m;
 c = (double*) malloc(sizeof(double));
 *c = 10;
 *p = c;
 a = (double*) malloc(sizeof(double)*5);
 a[0]=1.23;
  a[1]=2.46;
a[2]=3.69;
 a[3]=4.11;
 a[4]=7.21;
 *pa=a;
 for (m=0;m<5;m++)
 {
    b=a[m];
    b=b+1.0;
    a[m]=b;
  }
 } 

fortran。f:

 program test
  use iso_c_binding
  implicit none
 interface
  subroutine testc(pa, m) bind(c)
  use iso_c_binding
   type(c_ptr):: m
   type(c_ptr):: pa
  end subroutine testc
  end interface
  type(c_ptr) :: pa
  type(c_ptr) :: m
  real(c_double),pointer::fpa(:)
   real(c_double),pointer::fm(:)
    call testc(pa,m)
     call c_f_pointer(pa, fpa, [5])
     call c_f_pointer(m, fm, [1])
     print *, fm(1)
    print*, fpa(1)
   pause
 end program test