将数组从Fortran传递给C ++时未定义的引用

时间:2018-01-23 04:18:35

标签: c++ fortran intel-fortran

我正在努力将Fortran代码与C ++混合。我的主程序是用Fortran编写的。现在我正在传递数组,例如维度"AssetBundleManifest"到我的x(0:100,1)函数。我需要更改C ++函数中的值。然后返回数组。我搜索了一些解决方案。但他们没有工作。

Fortran部分:

C++

c ++ part:

integer m = 10
dimension x(0:100,1)
common /cart/ x
.... set the value for x
call cfun(m)

1 个答案:

答案 0 :(得分:1)

请改为尝试:

#include <stdio.h>
#include <math.h>
#include "defineMaxlen.h"

// because C is stupid.
typedef struct cart cart;

struct cart {
    double a[MAXINTERFACES][MAXLEN + 1]; // why do you need one more than you can use?
};

extern cart cart_;
#ifdef __cplusplus
extern "C"
#endif
int cfun_(int m)
{
    printf("x value: %f2.6\n ", cart_.a[0][5]);
    printf("From doublecart: \n");
    for (int i=0;i<m+1;i++)
    {
        cart_.a[0][i] = cos(cart_.a[0][i]);
    }

    printf("x NEW value: %f2.6\n ", cart_.a[0][5]);

    return 1;
}


#ifdef __cplusplus
}
#endif

解释

原始代码是用C编写的,但我假设用C ++编译器编译。这使函数cfun_成为一个C ++函数,包括名称修改。通过将函数包装在extern "C"中,函数名称不再受损,并且可以作为常规C函数访问。

struct不再包含在extern "C"中,因为这对您没有任何好处。我分别声明typedef struct cart cart;和定义struct cart {...}; - 我认为这是C中的最佳实践,因为在定义类型时C是愚蠢的。

变量cart_struct cart之外定义,以减少混淆。此外,我认为最好的做法之一。

注意:

我还没有对此进行编译,并且根本没有对它进行过测试。