vard
vard

Reputation: 2302

Avoid global object in C++ library

I have some C++ library, providing native C API to its client. In fact this library is a wrapper around some class instance and API calls should operate with the same class instance, using it's public interface, for example:

// library API, using class methods internally
MYDLL_API uint8_t __stdcall init();
MYDLL_API uint8_t __stdcall release();
MYDLL_API uint8_t __stdcall setSomething();
MYDLL_API uint8_t __stdcall doSomething();

// some inernal class
class Foo{
public:
    void setSomething();
    void doSomething();
private
    // some state
};

The only way to provide all API calls ability to work with the same Foo instance I see is to use global instance of this class, singleton possible. I want to avoid using global variables, how could it be reached?

Upvotes: 0

Views: 164

Answers (2)

eerorika
eerorika

Reputation: 238351

One possibility is to return a void pointer of the instance that you create to the caller and have the caller pass that to all the functions. The library can cast that pointer to the proper type and call the methods on the instance.

It's not pretty, but you want a C API, so what can you expect.

Upvotes: 3

Paul Evans
Paul Evans

Reputation: 27577

Looks like a bad design, libraries should work in multi-threaded environments. This need for "all API calls ability to work with the same Foo instance" prevents that which is very bad.

Upvotes: 0

Related Questions