Using interface to export class from dll - c++

IClass (My interface):
#ifndef _ICLASS_H
#define _ICLASS_H
#include <sstream>
namespace Test
{
class __declspec(dllexport) IClass
{
public:
virtual ~IClass() {}
virtual bool Init(const std::string &path) = 0;
};
}
#endif
Class.h
#ifndef _CLASS_H
#define _CLASS_H
#include "IClass.h"
#include <memory>
#include <sstream>
#include <stdio.h>
namespace Test
{
class Class: public IClass
{
public:
Class();
~Class();
bool Init(const std::string &path);
};
}
#endif
Class.cpp
#include "Class.h"
namespace Test
{
Class::Class()
{
}
bool Class::Init(const std::string &path)
{
try
{
// do stuff
return true;
}
catch(std::exception &exp)
{
return false;
}
}
}
main (in exe, dll linked implicitly)
#include "IClass.h"
using namespace Test;
int main(int argc, char* argv[])
{
std::shared_ptr<IClass> test = std::make_shared<Class>(); // error: unreferenced Class
test->Init(std::string("C:\\Temp"));
}
At the moment Class is not declared
-> if I include Class.h to main following error occurs: LNK2019: unresolved external symbol: add class __declspec(dllexport) Class : public IClass resolve this linker issue, but is it ok to do it this way?
-> I also can't do this: std::shared_ptr<IClass> test = std::make_shared<IClass>();
(because it's not allowed to create an object of abstract class)
How can I solve this issue and is this best practise?

If you want your EXE to allocate a new "Class" object, the EXE code has to know the Class type. If you want to keep the Class type unknown from the EXE, one solution may be to export from your DLL a factory function, which will construct a Class object and return it as an IClass pointer.
See How to implement the factory pattern in C++ correctly

Related

How can I fix this callback include problem?

I am kind of new to C++ (and StackOverflow). I am trying to get something to work, but I have some #include problems.
I want to call a callback I made (from here), but I am struggling to do this.
This is my code so far. When I include child.hpp in the someclass.hpp file (because it needs information about Child for Callback<Child>), it has a looped include and the compiler crashes.
I have read about forward declarations (would be class Child; in the someclass.hpp file), and after trying I figured out this works, but I also read different opinions about this.
I have all .hpp files guarded with #ifndef CLASSNAME #define CLASSNAME ... #endif
Do I need to change my entire design, or what is the best option in my case?
base.hpp
#include "someclass.hpp"
class Base
{
protected:
unique_ptr<SomeClass> someClass;
};
base.cpp
#include "base.hpp"
Base::Base()
{
this->someClass = make_unique<SomeClass>();
}
child.hpp
#include "base.hpp"
class Child : public Base
{
public:
void callbackFunction(std::string data);
unique_ptr<Callback<Child>> callback;
};
child.cpp
#include "child.hpp"
void Child::callbackFunction(std::string data)
{
/*does something*/
}
Child::Child()
{
this->callback = make_unique<Callback<Child>>(this, &Child::callbackFunction);
//I can call this->callback->call(data); here without problems
this->someClass->setCallback(this->callback);
//^^^^^^^^^^^^^^^ == base.someClass
}
someclass.hpp
#include "child.hpp" // < does crash compiler due to loop
//> someclass.hpp uses child.hpp
//> child.hpp uses base.hpp
//> base.hpp uses someclass.hpp
// and thus loop
class SomeClass
{
public:
void someFunction(std::string data);
void setCallback(unique_ptr<Callback<Child>> callback);
unique_ptr<Callback<Child>> callbackInstance;
};
someclass.cpp
//not 100% sure about the type of this parameter
void setCallback(unique_ptr<Callback<Child>> callback)
{
this->callbackInstance = callback;
}
void SomeClass::someFunction(std::string data)
{
//here I want to call this "Child::callbackFunction" which should go like "this->callbackInstance->call(data)" ?
}
also in someclass.hpp
template<class T>
class Callback
{
public:
Callback(T* instance, void (T::*function)(std::string))
{
this->callbackInstance = instance;
this->callback = function;
}
void call(std::string data)
{
(callbackInstance->*callback)(data);
}
private:
T *callbackInstance;
void (T::*callback)(std::string);
};
To solve the mentioned error("expected class-name before '{' token on child.hpp") you should remove the #include "someclass.hpp" from base.hpp and replace it with a forward declaration for class SomeClass as shown below.
base.hpp
#ifndef BASE_H
#define BASE_H
//NO NEED TO INCLUDE someclass.hpp
#include <memory>
class SomeClass;//FORWARD DECLARE SomeClass
class Base
{
std::unique_ptr<SomeClass> someClass;
public:
//add declaration for default constructor
Base();
};
#endif
base.cpp
#include "base.hpp"
#include "someclass.hpp"
//other things here
Base::Base()
{
this->someClass = std::make_unique<SomeClass>();
}
child.hpp
#ifndef CHILD_H
#define CHILD_H
#include "base.hpp"
#include <memory>
#include "someclass.hpp"
class Child : public Base
{
public:
void callbackFunction(std::string data);
std::unique_ptr<Callback<Child>> callback;
//add declaration for default constrcutor
Child();
};
#endif
child.cpp
#include "child.hpp"
void Child::callbackFunction(std::string data){
/*does something*/
}
Child::Child()
{
this->callback = std::make_unique<Callback<Child>>(this, &Child::callbackFunction);
//I can call this->callback->call(data); here without problems
}
someclass.hpp
#ifndef SOMECLASS_H
#define SOMECLASS_H
#include <string>
//REMOVED include child.hpp from here
class SomeClass
{
public:
void someFunction(std::string data);
//I think I need an instance of Callback<Child> here?
};
template<class T>
class Callback
{
public:
Callback(T* instance, void (T::*function)(std::string))
{
this->callbackInstance = instance;
this->callback = function;
}
void call(std::string data)
{
(callbackInstance->*callback)(data);
}
private:
T *callbackInstance;
void (T::*callback)(std::string);
};
#endif
someclass.cpp
#include "someclass.hpp"
void SomeClass::someFunction(std::string data)
{
//here I want to call this "Child::callbackFunction" which should go like "this->callbackInstance->call(data)" ?
}
The above program compiles and executes successfully as can be seen here.
Summary
Some of the changes that i made are listed below:
Removed unnecessary includes
Added declarations for default constructor in child.hpp and base.hpp
Added include guards in all headers.

OMNET++ How to retain all functions in AODVRouting class but override sendAODVPacket function only?

I'm writting a simple module to simulate a misbehaved node that inherits all functions from AODRouting, and overriding sendAODVPacket function by dropping the AODV packet once it has received it. The .h file as follows:
#ifndef __PROJECT1_SELFISHBASENODE_H_
#define __PROJECT1_SELFISHBASENODE_H_
#include <omnetpp.h>
#include "AODVRouting.h"
using namespace inet;
class SelfishBaseNode : public AODVRouting
{
protected:
virtual void initialize();
virtual void sendAODVPacket(AODVControlPacket *packet, const L3Address& destAddr, unsigned int timeToLive, double delay) override;
};
#endif
The CC file as follows:
#include "SelfishBaseNode.h"
#include <string.h>
#include <omnetpp.h>
Define_Module(SelfishBaseNode);
void SelfishBaseNode::initialize()
{
}
void SelfishBaseNode::sendAODVPacket(AODVControlPacket *packet, const L3Address& destAddr, unsigned int timeToLive, double delay)
{
EV << "Received message, dropping message now\n";
delete packet;
}
.NED file as follows:
package project1;
import inet.node.aodv.AODVRouter;
module snode extends AODVRouter
{
parameters:
//#networkNode;
#display("i=device/wifilaptop");
#labels(wireless-node);
#class(SelfishBaseNode);
submodules:
bad: SelfishBaseNode {
#display("p=273,350");
}
}
When I rebuild my project, i got these error:
SelfishBaseNode.h:35:18: error: 'sendAODVPacket' marked 'override' but does not override any member functions.
Any ideas how to fix this?
The method sendAODVPacket() is declared in AODVRouting.h without virtual. You should add virtual before declaration of sendAODVPacket() in AODVRouting class in AODVRouting.h

C++ determine best way for external class pointer

For a c++ application which I'm currently being busy to develop, I have several classes which I need to access through my entire code, without creating a new object
So searching I have found that one of methods that can be used is with the extern linkage specifier.
I would like to know what is best way to use this extern method, I wrote a little sample code
classone.h
#ifndef CLASSONE_H
#define CLASSONE_H
class ClassOne
{
public:
ClassOne();
void showClassOneInt();
private:
int m_classOneInt;
};
extern ClassOne *classOne;
---------------------------------------
classone.cpp
#include "classone.h"
#include <QDebug>
ClassOne *classOne;
ClassOne::ClassOne()
{
m_classOneInt = 1;
}
void ClassOne::showClassOneInt()
{
qDebug() << "ClassOneInt: " << m_classOneInt;
}
---------------------------------------
classtwo.h
#ifndef CLASSTWO_H
#define CLASSTWO_H
class ClassTwo
{
public:
ClassTwo();
void showClassTwoInt();
private:
int m_classTwoInt;
};
#endif // CLASSTWO_H
---------------------------------------
classtwo.cpp
#include "classtwo.h"
#include <QDebug>
ClassTwo::ClassTwo()
{
m_classTwoInt = 2;
}
void ClassTwo::showClassTwoInt()
{
qDebug() << "ClassTwoInt: " << m_classTwoInt;
}
---------------------------------------
classthree.h
#ifndef CLASSTHREE_H
#define CLASSTHREE_H
class ClassThree
{
public:
ClassThree();
void showClassThreeInt();
private:
int m_classThreeInt;
};
#endif // CLASSTHREE_H
---------------------------------------
classthree.cpp
#include "classthree.h"
#include <QDebug>
ClassThree::ClassThree()
{
m_classThreeInt = 3;
}
void ClassThree::showClassThreeInt()
{
qDebug() << "ClassThreeInit: " << m_classThreeInt;
}
---------------------------------------
classtest.cpp
#include "classtest.h"
#include "classone.h"
#include "classtwo.h"
#include "classthree.h"
//Class one pointer already in header
//Class two
extern ClassTwo *classTwo;
//Class three
extern ClassThree *classThree;
ClassTest::ClassTest()
{
//Execute class one
classOne->showClassOneInt();
//Execute class two
classTwo->showClassTwoInt();
//Execute class three
classThree->showClassThreeInt();
}
---------------------------------------
main.cpp
#include <QCoreApplication>
#include "classone.h"
#include "classtwo.h"
#include "classthree.h"
#include "classtest.h"
//Class one pointer already in header file
//Class two pointer
ClassTwo *classTwo;
//Class three pointer
ClassThree *classThree;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//Create object for class one
classOne = new ClassOne;
//Create object for class two
classTwo = new ClassTwo;
//Create object for class three
ClassThree three;
classThree = &three;
//Create a classTest object
ClassTest test;
return a.exec();
}
Please could you tell me what is the best way, thanks for you help.
The best way is to not do it and instead use dependency injection.
If you choose to do it anyway, you should at least use getter/factory functions (i.e. ClassOne &getClassOne())) so you can:
be sure random code can't change the objects and
handle order of construction implicitly by constructing on first use (sometimes appropriate, sometimes not).
Having a global state is generally not a great idea, seek to eliminate it.
If that cannot be done, try the singleton pattern.
class Singleton
{
Singleton(); //keep constructors private to avoid creation by others
static Singleton inst;
public:
static Singleton& Instance() {return inst;}
};
Singleton Singleton::inst;

Simple code - Unresolved external symbol - c++

//class1.cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
class class1
{
public:
int var;
class1(int i)
{
var = i;
}
};
//class1.h:
#include <iostream>
#include <stdlib.h>
using namespace std;
class class1
{
public:
int var;
class1(int i = 0);
};
//main.cpp
#include <iostream>
#include <stdlib.h>
#include "class1.h"
using namespace std;
int main()
{
class1 a(5);
return 0;
}
error:
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall class1::class1(int)" (??0class1##QAE#H#Z) referenced in function _main
what the heck is going on? I swear I've made almost the exact same program before and It's worked.
Change class1.cpp to something like:
//class1.cpp
#include "class1.h"
class1::class1(int i) : var(i) {}
You don't want to define the class itself again -- just define the member functions in the implementation file.
Then you'll build it something like:
g++ main.cpp class1.cpp
[of course, substituting the correct compiler name for the compiler you're using]
Most likely you are not compiling both cpp files. Check your build settings and make sure that both main.cpp and class1.cpp are being compiled.
However you also have a serious problem. You are declaring class1 twice. Once in the header:
class class1
{
public:
int var;
class1(int i = 0);
};
... and again in the cpp:
class class1
{
public:
int var;
class1(int i)
{
var = i;
}
};
In C++ there should be exactly one declaration for a class (and exactly one definition).
The way it works is you declare the class in your header, as you have already done, and then you define the members in the cpp, like this:
class1.cpp
#include "class1.h"
class1::class1(int i)
{
var = i;
}

LNK2019 && LNK1120 errors when splitting my code in multiple files

My code is stored in a main.cpp file which contains the void main() function, and a class MyClass which I now want to split to another file. IDE is Microsoft Visual Studio 2008 Professional.
myclass.h
#include <tchar.h>
class MyClass {
public:
static bool MyFunction (TCHAR* someStringArgument);
};
myclass.cpp
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
public:
static bool MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}
};
bool MyClass::someProperty = false;
main.cpp
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "myclass.h"
void main () {
if (MyClass::MyFunction(TEXT("myString"))) {
_tprintf(TEXT("Yay\n"));
}
}
However, when I try to run it, I get two linker errors.
LNK2019: unresolved external symbol ... (mentions MyClass::MyFunction)
LNK1120: 1 unresolved externals
What can I do to prevent these linker errors?
You declared two classes here. One of them is in myclass.h and the other is in myclass.cpp. Try the following instead:
myclass.h
#ifndef myclass_h_included
#define myclass_h_included
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode ();
public:
static bool MyFunction (TCHAR* someStringArgument);
};
#endif //!myclass_h_included
myclass.cpp
#include "myclass.h"
/*static*/ bool MyClass::someProperty = false;
void
MyClass::doSomeOneTimeCode() {
//...
}
bool
MyClass::MyFunction(TCHAR* someStringArgument) {
//...
}
Your main.cpp can stay the same. I would pay attention to UncleBens reply as well. One time initialization code should be hidden if at all possible.
Yo can't split a class definition in parts. It must be defined as a whole in one place. If you want to just have some methods of the class defined create a interface class that the MyClass class will later inherit. You should put the class' definition in a header file (myclass.h) and it's implementation in a cpp file (myclass.cpp). That way you can include the "myclass.h" in your main cpp file and use the class in your main function (which should be int main() or int main( int argc, char *argv[] )).
Strange that you didn't get a compiler error, as you are redefining MyClass.
Definitions (implementations) go into the cpp, and they are defined like this:
#include "myclass.h"
//helper functions, particularly if static, don't need to be in the class
//unnamed namespace means this stuff is available only for this source file
namespace
{
bool someProperty;
void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
}
bool MyClass::MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}