Static in a DLL is initialized and then not anymore - c++

I am encountering a very strange issue in my code... I've spent now a whole afternoon and cannot get nor heads nor tails on it. But maybe someone here can point me what I'm doing wrong.
So for the explanation:
I have a DLL.
In it I have 2 classes:
class Plugin {
public:
Plugin() : isInited(false) { all_plugins.push_back(this); }
virtual ~Plugin() { }
virtual int OnInit(ONINIT_PARAMS) { return 0; }
virtual void OnDeInit(ONDEINIT_PARAMS) { }
virtual int OnTick(ONTICK_PARAMS) { return 0; }
private:
static std::vector<Plugin*> all_plugins;
private: // NO COPY CLASS
Plugin(const Plugin&);
const Plugin& operator=(const Plugin&);
};
This class is responsible for mapping the Init/DeInit/Tick function-calls which comes from the main application.
Secondly I have this:
class DynamicModule {
public:
DynamicModule() : isLoaded(false) { all_modules.push_back(this); }
virtual ~DynamicModule() { }
virtual int OnLoad() { return 0; };
virtual int OnUnload() { return 0; };
private:
static std::vector<DynamicModule*> all_modules;
private: // NO COPY CLASS
DynamicModule(const DynamicModule&);
const DynamicModule& operator=(const DynamicModule&);
};
#define IMPLEMENT_DYNAMICMODULE std::vector<DynamicModule*> DynamicModule::all_modules;
Now in plugin.cpp I do:
IMPLEMENT_DYNAMICMODULE;
std::vector<Plugin*> Plugin::all_plugins;
That takes care of the static stuff.
Now I define a class (in a header file):
class InMarket : public Plugin {
public:
int OnInit (ONINIT_PARAMS);
void OnDeInit(ONDEINIT_PARAMS);
int OnTick (ONTICK_PARAMS);
private:
};
And implement it in a C++ file:
static class InMarket _InMarket;
I traced it, and the constructor gets called correctly. And inserted into Plugin::all_plugins.
Then I continue tracing, and I see the modules (2 at the moment, defined for example like the next example [in a C++ file]):
static class MQL4Trade : public DynamicModule {
public:
virtual int OnLoad() {
__OrderSend = (_OrderSend)GetProcAddress(exe, "OrderSend");
__OrdersCount = (_OrdersCount)GetProcAddress(exe, "OrdersCount");
return 0;
}
} _MQL4Trade;
I see these modules get inserted as well nicely in DynamicModule::all_modules.
But at the same time when I see this, I also noticed the Plugin::all_plugins has a {size=0}?!
Then when I enter my OnInit() function, I see that all_modules has a size of 2, and all_plugins = 0. Even though ALL of the constructors had been called?
I load my library as:
HMODULE plugin = LoadLibrary(pluginFilename.c_str());
All static objects constructors are called....
And I don't see ANY differences between the 2 things.
What is going on here?

Related

Calling private member of inherited class for unittest

I'm trying to write a unittest but I'm running into some problems.
I've got a class which has an int to keep track of the current state. All classes that are inherited of this class can change the state by calling the protectedFunction.
class RandomClass
{
public:
RandomClass()
{
mState = 0;
}
protected:
void protectedFunction()
{
++mState;
}
private:
int mState;
friend void UNITTEST_setMState(int state);
friend int UNITTEST_getMState();
};
Now i'd like to write a unittest for this class. So I created a new class which inherits the previous class. To Properly test all the states I need to set the state, and I need to get the state to assert it. I've tried using a friend function but it does not seem to work.
class UnittestRandomClass : public RandomClass
{
public:
void wrapperProtectedFunction()
{
protectedFunction();
}
void UNITTEST_setMState(int state)
{
this->mState = state; // Apparently not like this
}
int UNITTEST_getMState()
{
return this->mState; // Apparently not like this
}
};
int main() {
UnittestRandomClass ut;
ut.UNITTEST_setMState(1);
ut.wrapperProtectedFunction();
int res = ut.UNITTEST_getMState();
ASSERT_EQ(res, 2);
}
I seem to be doing something wrong, as the mState still appears to be private and thus I'm getting an inaccessible error. I've also tried calling it directly by just returning mState, but the same error applies.
One solution would be to move the mState to protected, but as there are other classes which inherit the RandomClass, I do not think that would be a save solution.
So how would I be able to solve such an issue and resolve my errors?
For future viewers here is the working code:
class RandomClass
{
public:
RandomClass()
{
mState = 0;
}
void publicFunction();
protected:
void protectedFunction()
{
++mState;
}
private:
int mState;
friend class UnittestRandomClass;
};
class UnittestRandomClass : public RandomClass
{
public:
void wrapperProtectedFunction()
{
protectedFunction();
}
void setMState(int state)
{
mState = state;
}
int getMState()
{
return mState;
}
};
int main() {
UnittestRandomClass ut;
ut.setMState(1);
ut.wrapperProtectedFunction();
int res = ut.getMState();
ASSERT_EQ(res, 2);
}
Your class declares a free-standing function to be friend.
Your unit test uses a member function of a class, the class is not declared friend.
You can write friend class UnitTestRandomClass;
Specifically, what you want to do, make a member function of a future derived class a friend is not provided by the standard. There is no syntax for that.

How to Skip a Portion of the ”Code” in the source code while doing GoogleTest

I tried using a debug flag addition (GOOGLE_TEST) in the source code and defined it in the TEST/Makefile.am. but the things didn’t work. I am using C++ Language.
Note: I don’t want to change anything in the SRC Directory code which will affect the production code and its Makefile.am
Test Class in SRC Directory
class Common: public Thread {
public:
friend class test_common;
Common {
}
~Common () {
}
virtual void ThreadMain();
protected:
virtual void ProcessData(void);
};
void Common::ProcessData(void) {
#ifndef __GOOGLE_TEST__
while (1) { }
#endif
}
TESTCODE in test Directory
class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
Common commonObj();
commonObj. ProcessData ();
}
OUTPUT
GTest Stuck in the While loop part even after defining the flag in the test/makefile.am
Dont rely on the compilation flags, without affecting the production code use the GMOCK methods to get rid off the while (1) loop , the code can go like below:
TESTCODE:
class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
Common commonObj();
ON_CALL(mock_if, GetBool())
.WillByDefault(Return(true));
EXPECT_CALL(mock_if, GetBool())
.Times(AtLeast(1))
.WillOnce(Return(true))
.WillOnce(Return(false));
commonObj. ProcessData ();
}
ABSTRACT CODE:
class AbstractIf {
public:
AbstractIf (void) = default;
virtual ~AbstractIf (void) = default;
virtual bool GetBool() = 0;
};
MOCK CODE:
class MockIf : public AbstractIf {
public:
MOCK_METHOD0(GetBool,bool());
};
SOURCE CODE:
class Common: public Thread {
public:
friend class test_common;
Common {
}
~Common () {
}
virtual void ThreadMain();
protected:
virtual void ProcessData(void);
AbstractIf *prov_fl_if_;
};
void Common::ProcessData(void) {
while (prov_fl_if_->GetBool()) { }
}
By this way we can skip the part of the code we want without affecting the production code
There is no way to make a #define value from one compilation unit affect the compilation of another, previously compiled units. Given the list of things you have stipulated you don't want to do, you will have to use some form of runtime shenanigans.
You could make ProcessData take an argument that determines whether the loop should iterate:
void ProcessData(bool once=false);
void Common::ProcessData(bool once) {
do {
// ... your loop code
} while (!once);
}
Or you could use a global variable that is defined in the module with your main() in it, lets call it main.cpp.
Production main.cpp:
const bool g_isDebugMode = false;
Unit test main.cpp:
const bool g_isDebugMode = true;
main.h
extern const bool g_isDebugMode;
now you can write runtime tests against this variable.
do {
// your code
} while (g_isDebugMode == false);

Linker error while implementing Adapter design pattern

I am getting linker error in the code below.
If I make the ClientInterface's ClientAPI() function as pure virtual, then the linker error disappears.
What is the reason for this behavior?
// How the interface looks like to the Client
class ClientInterface
{
public:
virtual void ClientAPI();
virtual ~ClientInterface(){}
};
template <class TYPE> //this adaptor class can adapt to any type of legacy application as it is a generic function that uses template parameter to point to any legacy application
class Adaptor : public ClientInterface
{
public:
Adaptor(TYPE *objPtr, void (TYPE:: *fnPtr)())
{
m_objPtr = objPtr;
m_fnPtr = fnPtr;
}
void ClientAPI()
{
/*....
Do the conversion logic reqd to convert the user params into the params expected by your original legacy application...
....*/
(m_objPtr->*m_fnPtr)(); //Would call the method of the legacy application internally
}
~Adaptor()
{
if(m_objPtr)
delete m_objPtr;
}
private:
TYPE *m_objPtr; //You can keep either pointer to the Legacy implementation or derive the Legacy implementation privately by your Adaptor class
void (TYPE:: *m_fnPtr)();
};
//Adaptee classes below..
class LegacyApp1
{
public:
void DoThis()
{
cout<<"Adaptee1 API"<<endl;
}
};
//Execution class where main is defined and i have include the "Adaptor.h"
#include "headers.h"
#include "Adaptor.h"
void Adapter()
{
ClientInterface **interface_ptr = new ClientInterface *[2];
interface_ptr[0] = new Adaptor<LegacyApp1>(new LegacyApp1() , &LegacyApp1::DoThis);
interface_ptr[1] = new Adaptor<LegacyApp2>(new LegacyApp2() , &LegacyApp2::DoThat);
for(int i = 0; i < 2 ; i++)
{
interface_ptr[i]->ClientAPI();
}
}
int main()
{
//Testing();
Adapter();
char ch;
cin>>ch;
return 0;
}
So the correction in the above code is as follows: Just make the following changes to first few lines of the original code.
// How the interface looks like to the Client
class ClientInterface
{
public:
//earlier I forgot to define it, so it was giving linker error as the function is just declared but not defined.
virtual void ClientAPI(){}
virtual ~ClientInterface(){}
};
Thanks.

In what order are methods called when you have class hierarchy?

Consider:
class Mobile {
double memory_util;
public:
virtual void power_save(double duration) = 0;
};
class Laptop : public Mobile {
bool is_unlocked;
protected:
bool is_charged;
public:
void power_save(double duration);
virtual double remaining_time();
};
class NegativeNumber {};
class IPad : public Laptop {
int generation;
public:
void power_save(double duration);
bool isJailBroken();
};
class HPLaptop : public Laptop {
int warranty_years;
public:
void extend_warranty(int years);
};
class HPdv6 : public HPLaptop {
bool repaired;
public:
double remaining_time(){ return HPLaptop::remaining_time(); }
bool is_repaired { return repaired; }
};
And you wanted to do the following:
int main () {
Mobile* d = new HPdv6();
Laptop *s = d;
d->power_save(100);
cout << “remaining operation time: ” <<
s->remaining_time() << endl;
return 0;
}
Which methods would actually be called here? I understand that Mobile is a virtual function, but I'm unsure how to deal with the class hierarchy when you have pointers like this. Are there any tips about class hierarchy that will make problems that deal with various inherited classes easier to understand?
Thank you.
Once you sorted out the error in Laptop *s = d; (see static_cast<>()), you would find that HPdv6's remaining_time() would be called and Laptop's power_save() would be called.
To over-simplify, the functions are resolved by starting at HPdv6 and walking up the inheritance tree until the method is found. IPad won't be used because it doesn't appear between HPdv6 and Laptop, it sits in a separate branch.
If you want the non-oversimplified version, look up vtables. Here is the Wikipedia article on them: http://en.wikipedia.org/wiki/Virtual_method_table

Several C++ classes need to use the same static method with a different implementation

I need several C++ classes to have a static method "register", however the implementation of register varies between those classes.
It should be static because my idea is to "register" all those classes with Lua (only once of course).
Obviously I can't declare an interface with a static pure virtual function. What do you guys suggest me to do ? Simplicity is welcome, but I think some kind of template could work.
Example of what I would like to achieve
class registerInterface
{
public:
static virtual void register() = 0; //obviously illegal
};
class someClass: public registerInterface
{
static virtual void register()
{
//I register myself with Lua
}
}
class someOtherClass: public registerInterface
{
static virtual void register()
{
//I register myself with Lua in a different way
}
}
int main()
{
someClass::register();
someOtherClass::register();
return 0;
}
Based on how you've described the problem, it's unclear to me why you even need the 'virtual static method' on the classes. This should be perfectly legal.
class SomeClass {
static void register(void) {
...
}
}
class SomeOtherClass {
static void register(void) {
...
}
}
int main(int argc, char* argv[]) {
SomeClass::register();
SomeOtherClass::register();
return 0;
}
Drop the RegisterInterface, I don't think you need it.
If it helps, you could take Hitesh's answer, and add:
struct luaRegisterManager {
template <typename T>
void registrate() {
T::registrate();
// do something else to record the fact that we've registered -
// perhaps "registrate" should be returning some object to help with that
}
};
Then:
int main() {
luaRegisterManager lrm;
lrm.registrate<someClass>();
lrm.registrate<someOtherClass>();
}
More generally, if you want to introduce any dynamic polymorphism in C++, then you need an object, not just a class. So again, perhaps the various register functions should be returning objects, with some common interface base class registeredClass, or classRegistrationInfo, or something along those lines.
Could provide an example of what you feel it is that you need dynamic polymorphism for? Hitesh's code precisely matches your one example, as far as I can see, so that example must not cover all of your anticipated use cases. If you write the code that would be using it, perhaps it will become clear to you how to implement it, or perhaps someone can advise.
Something else that might help:
#include <iostream>
#include <string>
#include <vector>
struct Registered {
virtual std::string name() = 0;
virtual ~Registered() {}
Registered() {
all.push_back(this);
}
static std::vector<Registered*> all;
};
std::vector<Registered*> Registered::all;
typedef std::vector<Registered*>::iterator Iter;
template <typename T>
struct RegisteredT : Registered {
std::string n;
RegisteredT(const std::string &name) : n(name) { T::registrate(); }
std::string name() { return n; }
// other functions here could be implemented in terms of calls to static
// functions of T.
};
struct someClass {
static Registered *r;
static void registrate() { std::cout << "registering someClass\n"; }
};
Registered *someClass::r = new RegisteredT<someClass>("someClass");
struct someOtherClass {
static Registered *r;
static void registrate() { std::cout << "registering someOtherClass\n"; }
};
Registered *someOtherClass::r = new RegisteredT<someOtherClass>("someOtherClass");
int main() {
for (Iter it = Registered::all.begin(); it < Registered::all.end(); ++it) {
std::cout << (*it)->name() << "\n";
}
}
There are all sorts of problems with this code if you try to split it across multiple compilation units. Furthermore, this kind of thing leads to spurious reports from memory leak detectors unless you also write some code to tear everything down at the end, or use a vector of shared_ptr, Boost pointer vector, etc. But you see the general idea that a class can "register itself", and that you need an object to make virtual calls.
In C++ you usually try to avoid static initialisation, though, in favour of some sort of setup / dependency injection at the start of your program. So normally you would just list all the classes you care about (calling a function on each one) rather than try to do this automatically.
Your intentions are noble, but your solution is inkling towards "overengineering" (unless I am missing an obvious solution).
Here is one possibility: You can use the Virtual Friend function idiom For example,
class RegisterInterface{
friend void register(RegisterInterface* x){x->do_real_register();}
protected:
virtual void do_real_register();
}
class Foo : public RegisterInterface{
protected:
virtual void do_real_register(){}
};
class Bar : public RegisterInterface{
protected:
virtual void do_real_register(){}
};
int main(int argc, char* argv[]) {
BOOST_FOREACH(RegisterInterface* ri, registered_interfaces)
{
register(ri);
}
return 0;
}
I know you've already accepted an answer, but I figured I would write this up anyway. You can have self-registering classes if you use some static initialization and the CRTP:
#include <vector>
#include <iostream>
using namespace std;
class RegisterableRoot // Holds the list of functions to call, doesn't actually need
// need to be a class, could just be a collection of globals
{
public:
typedef void (*registration_func)();
protected:
static std::vector<registration_func> s_registery;
public:
static void do_registration()
{
for(int i = 0; i < s_registery.size(); ++i)
s_registery[i]();
}
static bool add_func(registration_func func) // returns something so we can use it in
// in an initializer
{
s_registery.push_back(func);
return true;
}
};
template<typename RegisterableType> // Doesn't really need to inherit from
class Registerable : public RegisterableRoot // RegisterableRoot
{
protected:
static const bool s_effect;
};
class A : public Registerable<A> // Honestly, neither does A need to inherit from
// Registerable<T>
{
public:
static void Register()
{
cout << "A" << endl;
}
};
class B : public Registerable<B>
{
public:
static void Register()
{
cout << "B" << endl;
}
};
int main()
{
RegisterableRoot::do_registration();
return 0;
}
std::vector<RegisterableRoot::registration_func> RegisterableRoot::s_registery;
template <typename RegisterableType> // This is the "cute" part, we initialize the
// static s_effect so we build the list "magically"
const bool Registerable<RegisterableType>::s_effect = add_func(&RegisterableType::Register);
template class Registerable<A>; // Explicitly instantiate the template
// causes the equivalent of
// s_registery.push_back(&A::Register) to
// be executed
template class Registerable<B>;
This outputs
A
B
although I wouldn't rely on this order if I were you. Note that the template class Registerable<X> need not be in the same translation unit as the call to do_registration, you can put it with the rest of your definition of Foo. If you inherit from Registerable<> and you don't write a static void Register() function for your class you'll get a (admittedly probably cryptic) compiler error much like you might expect if there really was such a thing as "static virtuals". The "magic" merely adds the class specific function to the list to be called, this avoids several of the pitfalls of doing the actual registration in a static initializer. You still have to call do_registration for anything to happen.
How about this way? Define an interface class:
// IFoobar.h
class IFoobar{
public:
virtual void Register(void) = 0;
}
Then define the class that handles the register..
// RegisterFoobar.h
class RegisterFoobar{
public:
// Constructors etc...
IFoobar* fooBar;
static void RegisterFoobar(IFoobar& fubar){
foobar = &fubar;
}
private:
void Raise(void){ foobar->Register(); }
}
Now, then define another class like this
// MyFuBar.h
class MyFuBar : IFoobar{
public:
// Constructors etc...
void Register(void);
private:
RegisterFoobar* _regFoobar;
}
Call the code like this:
//MyFuBar.cpp
MyFuBar::MyFuBar(){
_regFoobar = new Foobar();
_regFoobar->RegisterFoobar(this);
}
void MyFuBar::Register(void){
// Raised here...
}
Maybe I have misunderstood your requirements...