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