本帖最后由 kyra 于 2017-7-14 08:20 编辑
问题1,无需额外处理。
问题2,不能在type里存放fortran语言的动态分配数组。否则C语言无法用标准化的手段访问。解决办法是,用 C 指针,fortran分配后把地址赋给 C 指针。具体看注释
(这方法适合于fortran的动态分配返回给 C,并不适合 C 分配的数组传递给 fortran)
[Fortran] 纯文本查看 复制代码 module hydromodelUtil
use iso_c_binding
implicit none
double precision, parameter :: pi=acos(-1.d0)
!这部分为输出值
type ,Bind(C):: singleinfo
integer(c_int) :: controlno
integer(c_int) :: unittype
integer(c_int) :: solid
real(c_double) :: coearea
real(c_double):: volume
real(c_double), dimension(3) :: center
integer (c_int):: pointcount, trianglecount
type(C_PTR) :: pointchain , trianglechain!!!!!!!用C指针
end type singleinfo
contains
subroutine cylindermeshing(r, h, cylinderinfo) Bind(C,Name="cylindermeshing")
!DEC$ ATTRIBUTES DLLEXPORT::cylindermeshing
implicit none
real(c_double) :: r, h
type(singleinfo) :: cylinderinfo
integer(c_int) :: polyedge=60
double precision, dimension(:,:), allocatable :: point
double precision, dimension(:,:), allocatable , target ,save :: pointchain!!!!!!!Fortran分配数组
real(c_double) :: dtheta
integer(c_int) :: meshi
dtheta=2*pi/real(polyedge)
cylinderinfo%volume=(0.5d0*polyedge*sin(dtheta)*r**2)*h
cylinderinfo%center=(/ 0.0d0, 0.0d0, 0.5d0*h /)
cylinderinfo%pointcount=2*polyedge
cylinderinfo%trianglecount=4*polyedge
allocate(point(2,polyedge+1) )
allocate(pointchain(3,cylinderinfo%pointcount) )!!!!!!!
do meshi=1, polyedge, 1
point(1,meshi)=r*cos( (real(meshi)-1.0d0)*dtheta)
point(2,meshi)=r*sin( (real(meshi)-1.0d0)*dtheta)
end do
point(:, polyedge+1)=point(:, 1)
do meshi=1, polyedge, 1
pointchain(1:2,meshi)=point(1:2,meshi)
pointchain(3,meshi)=0.0d0
pointchain(1:2,polyedge+meshi)=point(1:2,meshi)
pointchain(3,polyedge+meshi)=h
end do
cylinderinfo%pointchain = c_loc( pointchain )!!!!!!!把地址给C指针
end subroutine cylindermeshing
end module hydromodelUtil
[C++] 纯文本查看 复制代码 #include <iostream>
struct singleinfo{
int controlno;
int unittype;
int solid;
double coearea;
double volume;
double center[3];
int pointcount , trianglecount;
double *pointchain , *trianglechain;/////// C 指针
};
extern "C" {
void cylindermeshing( double & , double & , struct singleinfo * );
double thirddet( double * );
}
using namespace std;
int main()
{
struct singleinfo cylinderinfo;
double r = 3.0;
double h = 4.0;
cylinderinfo.controlno = 1;
cylinderinfo.unittype = 2;
cylinderinfo.solid = 3;
cylinderinfo.coearea = 4;
cylinderinfo.volume = 5;
cylinderinfo.unittype = 6;
cylinderinfo.pointcount = 7;
cylinderinfo.trianglecount = 8;
cylinderinfo.center[0] = 11;
cylinderinfo.center[1] = 11;
cylinderinfo.center[2] = 11;
cylindermeshing(r, h, &cylinderinfo);
double deta[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
deta[j][i] = j*4 + i;
}
}
cout << cylinderinfo.pointchain[0] << endl;
}
|