Domanda

I need to mix Fortran and C++ together. I have written C++ class. I am able to call C++ public function thanks to extern "C" function that makes call to C++ library.

This function creates some instances of this C++ classe. When this function ends, I want to keep those instances in memory to call them after. But destruction my instances are called automatically.

I don't want to use those instances with Fortran but to use them in other wrapped C++ function. I can't use iso_c_binding or any Fortran 2003 function (unfortunately).

Do you have any simple ideas to keep instances in memory ?

Thanks in advance.

È stato utile?

Soluzione

If you want to access the same C++ objects again when you enter the same function the next time, you can declare them as static inside the function. This will make each invocation of the function share the same set of (static) variables.

If multiple functions need access to the same object(s), you can define them in the namespace scope (outside any function or class). All invocations of the functions that access the objects will share the same global variable(s).

If you don't want the implicit sharing of instances that is implied by making them global or static, the best option (the best option anyway) is to write a C wrapper around the class complete with create/destroy functions that dynamically allocate an instance of the class. For example:

// x.hpp
class X {
public:
    X(int);
    void foo();
};

// x_wrapper.h
extern "C" {
void* create_x(int arg);
void destroy_x(void* anX);
void x_foo(void* anX);
}

// x_wrapper.cpp
#include "x.hpp"
#include "x_wrapper.h"

void* create_x(int arg) {
    return new X(arg);
}

void destroy_x(void* anX) {
    X* self = (X*)anX;
    delete self;
}

void x_foo(void* anX) {
    X* self = (X*)anX;
    return self->foo();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top