简体   繁体   中英

Using a C++ class object in fortran 77

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;
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM