Take the 2-minute tour ×

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.

share|improve this question
new? (Also, what does this have to do with Fortran?) –  melpomene Dec 10 '12 at 17:02
So they are being created on the stack, and then destroyed when your function completes? Put them on the heap (using new, but best to avoid using it directly with some wrapper), and then save pointers to them somewhere. –  BoBTFish Dec 10 '12 at 17:02
add comment

1 Answer

up vote 1 down vote accepted

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 {
    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();
share|improve this answer
The first two options are terrible, but you saved your answer by writing a decent example. Although it would be better if the function definitions were also wrapped in extern "C" (not strictly necessary, but you never know when you decide to not include the x_wrapper.h header in x_wrapper.cpp for some reason, leading to mysterious linker errors. –  rubenvb Dec 10 '12 at 19:07
add comment

Your Answer


