Using a C++ class object in fortran 77

时间秒杀一切 提交于 2019-12-08 04:50:15

问题


Is there a way to pass a C++ object to use with Fortran 77? For example:

C23456
      program main
      write (*,*) 'Hello from FORTRAN 77!'
      call readstep('cube.stp'//CHAR(0),myshape)
      stop
      end

and then use the myshape as a C++ object which will just be kept in memory used by Fortran and to just pass it to other C++ functions that will actually use it?

EDIT: Here is the C++ code:

extern"C" {
    void readstep_(char*,void*);
}

void readstep_(char* inputFile, void* outShape){

    STEPControl_Reader reader;
    reader = STEPControl_Reader();

    int succeed = reader.ReadFile(inputFile);

    if(!succeed){
        std::cout << "There was an error with the input file" << std::endl;
        return;
    }

    reader.NbRootsForTransfer();
    reader.TransferRoots();

    TopoDS_Shape myShape = reader.OneShape();
    TopoDS_Shape* myShapePtr = new TopoDS_Shape();
    (*myShapePtr) = myShape;

    outShape = myShapePtr;

    return;
}

回答1:


Please read tag description of the tag https://stackoverflow.com/questions/tagged/fortran-iso-c-binding for much better options. And the many questions and answers there.

I will use the star notation as a common extension.

C++:

class Obj{

};

extern "C" {
  void hello_();


  void readstep_(char* name, Obj** ptr){
    *ptr = new Obj(); //use name in the actual process
  }
  void pass_it_(Obj** ptr){
    hello_();
    delete *ptr; //some usage of the object
  }

}

It uses pointer to pointer because of the pass by reference.

fortran:

  program main

    integer*8 myshape

    call readstep('cube.stp'//CHAR(0),myshape)

    call pass_it(myshape)

  end

  subroutine hello
    write (*,*) 'Hello from FORTRAN 77!'
  end subroutine

Use integer*4 on a 32-bit platform. (note there is no reason for the STOP statement)

compile:

g++ f77c++.f f77c++.C -lgfortran

or

gfortran f77c++.f f77c++.C -lstdc++

> ./a.out 
 Hello from FORTRAN 77!


来源:https://stackoverflow.com/questions/24761552/using-a-c-class-object-in-fortran-77

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!