C++/Omnet++ Function is ignored in VeinsInetSampleApplication, veins_inet - c++

I don't know whether I don't get the logic behind adding a function to eclipse/omnet++:
Tried to simply add a new function "init_func" to the VeinsInetSampleApplication.h Header file
#pragma once
#include "veins_inet.h"
#include "VeinsInetApplicationBase.h"
class VEINS_INET_API VeinsInetSampleApplication : public veins::VeinsInetApplicationBase {
protected:
bool haveForwarded = false;
protected:
virtual bool startApplication() override;
virtual bool stopApplication() override;
virtual void processPacket(std::shared_ptr<inet::Packet> pk) override;
// ADAPTION 2022/05/28
virtual void init_func();
public:
VeinsInetSampleApplication();
~VeinsInetSampleApplication();
};
However when I simply copy the initialization code of the startApplication() function into "init_func()" in VeinsInetSampleApplication.cc "init_func()" is simply ignored by my simulation.
Here's the code snippet which basically shall send a message to all my simulation nodes at time t=5 sec. The only difference to the startApplication() function is that the message sending is triggered at t=5sec. and not at t=10sec.
The startApplication() function does its job correctly and even if i comment it out and only make my init_func() function run it is also ignored. (I tried this in order to rule out any issues with the "this" pointer etc. which would suggest there is a "bad interaction" between both functions). So it really seems like my init_func() is not registered. But I don't know. Does anybody have an idea why "init_func()" might be ignored here by Omnet++?
Code of init_func():
void VeinsInetSampleApplication::init_func()
{
// host[0] should stop at t=5s, change in timerManger.create(...)
if (getParentModule()->getIndex() == 0) {
auto callback = [this]() {
getParentModule()->getDisplayString().setTagArg("i", 1, "red");
traciVehicle->setSpeed(0);
auto payload = makeShared<VeinsInetSampleMessage>();
timestampPayload(payload);
payload->setChunkLength(B(100));
payload->setRoadId(traciVehicle->getRoadId().c_str());
auto packet = createPacket("accident");
packet->insertAtBack(payload);
sendPacket(std::move(packet));
};
timerManager.create(veins::TimerSpecification(callback).oneshotAt(SimTime(5, SIMTIME_S)));
}
}
(I also changed return type of "init_func" to bool to further increase similarity. But that of course was also not successful)
Best regards,
Lukas

init_func() is ignored because it is not called neither by initialize() nor by any other method. You decided to create a new method, so you have to add calling of that method somewhere in the code.

Related

How can I call non-existent functions in C++

So, I want to know how I can call functions from header...
To explain it better, I have a header file, which is something similar to a game library.
I want to call certain functions in the Main part of the program(the dynamic one), but I want these functions not to be required.
So, if I click a hotkey combo, I'd call a function in Main part of the program called "hotkeyHit", but first I need to check if it's there. I'm implementing some kind of an "Event system".
And that's where I hit the wall...
First of all I don't know how to check if there is that function in the Main, I can't compile if there is no function called that and last of all, I can't declare the same function for second time, which leaves me with no obvious options.
So now I'd like to know how I can do that so it would work the way I want it to.
Thanks in advance
Some example clode below to hopefully explain my comment. In this, the methods in the CBaseHandler class are intentionally empty. Your Event Handler takes a reference to a CBaseHandler and in this example tries to handle a keypress and a mouseclick. However, the concrete implementation of the handler, CHandler only implements the Keypress handler (in this case just by printing a string, but you can do whatever you want)
When the Event Handler runs, only the Keypress will do anything. Presumably you'll be wanting to call that in a loop of some description in real life.
The event handler loop in your library can now take any implementation of an event handler for whatever purposes you need.
#include <iostream>
class CBaseHandler
{
public:
virtual void handleKeyPress(int i)
{
}
virtual void handleMouseClick(int i)
{
}
};
class CHandler : public CBaseHandler
{
public:
virtual void handleKeyPress(int i)
{
std::cout << "Derived - KP" << std::endl;
}
};
void DoHandle(CBaseHandler& handler)
{
handler.handleKeyPress(4);
handler.handleMouseClick(0);
}
int main() {
CHandler myhandler;
DoHandle(myhandler);
}
If you have a function declared in header file but not defined anywhere, this will compile fine. However if you attempt to use this function anywhere in the code, the linker will complain when you try to compile it as it won't be able to find the definition. So you could simply add dummy definition which does nothing.
header.h
void myFunction();
source.cpp (1)
int main()
{
myFunction(); // linker error on compile
return 0;
}
source.cpp (2)
void myFunction() {}; // dummy definition
int main()
{
myFunction(); // no problem
return 0;
}
Ok, so after getting some help from you guys and figuring it out online, I've found a solution that works for me.
I've set it up like so:
Main code:
void mouseClicked();
void main(){
setMouseClicked(mouseClicked);
}
void mouseClicked();
Header code:
void (*mc)() = NULL;
void setMouseClicked(void (*fun)(void)){
mc = fun;
}
and then in the event function I do this:
void handleMousePress(int button, int state, int x, int y){
mouseX = x;
mouseY = y;
mouseButton = button;
if(state == GLUT_DOWN){
if(mc != NULL)
(*mc)();
}
}
I've worked on a compromise by having a declaration of the function in the main part of the code and having a setter for that function, but with that I've added an ability for renaming functions that are called when the event is triggered.
So once again, thanks for your suggestions, but at the end I've found that pointers to functions work the best.

Unreal Engine crash with AddDynamic

I have a problem with binding OnAudioFinished delegate.
Searched for some time but haven't find good answer yet. I've followed this answer!
My code compiles without any error at all, however when my project is loading it crashes with this errors:
UE4Editor_!TBaseDynamicMulticastDelegate<FWeakObjectPtr,void>::__Internal_AddDynamic<UAudioController>() [d:\path\delegates\delegatesignatureimpl.inl:1140]
UE4Editor_Project!UAudioController::UAudioController() [d:\path\private\audiocontroller.cpp:17]
UE4Editor_Project!InternalConstructor<UAudioController>()
What I do understand is that constructor crushes my engine, but i don't know why is that happening. Here is my code that is responsible for this binding.
.h
static UAudioComponent* AudioComponent;
public:
UAudioController();
void SoundFinished();
.cpp
UAudioController::UAudioController()
{
AudioComponent->OnAudioFinished.AddDynamic(this, &UAudioController::SoundFinished);
}
void UAudioController::SoundFinished()
{
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, TEXT("Audio Finished trigger"));
}
In UE, properties are not properly initialized during constructor run. They are when PostInitProperties is called (after load from CDO).
Also you should ask yourself if static class is necessary. If You need Singleton, you can store this in GameInstance. It is safer, especially in UE environment (you can't have static UPROPERTY() field etc.)
I believe that binding this event during BeginPlay should be sufficient. Removing is good practice, although not necesarry when using Dynamic binding
// AudioController.h
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReasonType) override;
// AudioController.cpp
void UAudioController::BeginPlay() {
Super::BeginPlay();
AudioComponent->OnAudioFinished.AddDynamic(this, &UAudioController::SoundFinished);
}
void UAudioController::EndPlay(const EEndPlayReason::Type EndPlayReasonType) {
AudioComponent->OnAudioFinished.RemoveDynamic(this, &UAudioController::SoundFinished);
Super::EndPlay(EndPlayReasonType);
}
EDIT: Since you named your class with Controller suffix, I suppose that this will be single occurence of this actor in level. So you don't need to have static pointer (it could get destroyed - again, this is UE speciality), just simply have AudioComponent as a public member in your controller:
// AudioController.h
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "My Audio Conmponent", meta = (AllowPrivateAccess = "true"))
UAudioComponent* AudioComponent;
and then correctly initialize it in constructor:
UAudioController::UAudioController()
: Super()
{
AudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("MyAudioComponent"));
}
or
UAudioController::UAudioController(const class FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
AudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("MyAudioComponent"));
}
Your component will be properly created and binded function will be executed as expected.
Also, as #JKovalsky mentioned, your SoundFinished method must be marked with UFUNCTION() macro when using Dynamic delegates.

C++ Setting member object which has const member

I am using OIS for handling my input with Ogre and currently, on KeyPress/Release a Message object like the following will be constructed and distributed among subscribers.
class Message
{
public:
Message();
~Message();
inline void SetKeyEvent(const OIS::KeyEvent& keyEvent) { _keyEvent = keyEvent; }
const OIS::KeyEvent& GetKeyEvent() const { return _keyEvent; }
private:
OIS::KeyEvent _keyEvent;
};
Since this object will be constructed/destroyed whenever input is received via keyboard, I am trying to store a pre-constructed Message object and then simply update the _keyEvent field with the new data, before distributing.
The problem is that the OIS::KeyEvent object has a const member which is preventing me from using the assignment operator. The SetKeyEvent method gives me the following syntax error:
function "OIS::KeyEvent::operator=(const OIS::KeyEvent &)" (declared implicitly) cannot be referenced -- it is a deleted function
I was wondering what the best way to achieve this functionality would be?
Thanks in advance
EDIT: Just to clarify, I already use initializer lists when possible. My intention is to have the Message object pre-constructed and then update the _keyEvent field with the new event data from the KeyPress event which OIS fires, using the SetKeyEvent method. I would like to know if this is possible and if so, what the best way to do it would be.
The copy operator is deleted, so you must work with pointers.
class Message
{
public:
Message();
~Message();
inline void SetKeyEvent(OIS::KeyEvent* keyEvent) { _keyEvent = keyEvent; }
const OIS::KeyEvent& GetKeyEvent() const { return _keyEvent; }
private:
OIS::KeyEvent* _keyEvent;
};
And now it's better to check if the argument in the setter isn't nullptr.
inline void SetKeyEvent(OIS::KeyEvent* keyEvent)
{
assert(keyEvent != nullptr);
_keyEvent = keyEvent;
}
assert() needs #include <assert.h>
EDIT:
Sorry, forgot the getter method. You must use pointers, too.
const OIS::KeyEvent* keyEvent = &Message.GetKeyEvent();
Where Message is your class instance.
It is possible by using placement new and an explicit destructor call, things you normally should never do:
inline void SetKeyEvent(const OIS::KeyEvent& keyEvent)
{
_keyEvent.~KeyEvent();
new (&_keyEvent) OIS::KeyEvent(keyEvent);
}
This is bad ugly horrible code, use at your own risk.

Implementing Pipeline Pattern, design and function pointer issue

I'm trying to write my own solution of the pipe and filter pattern with threads, I'd like some input. My current issue is that the library I am using(tinythread) expects a global function pointer to start a thread :
thread (void(*)(void *) aFunction, void * aArg )
My Stage class has a Process function that I wanted to pass as the function pointer.
class Stage
{
public:
void Process(void *aArg);
protected:
Stage(SharedBuffer *inPipe, SharedBuffer *outPipe);
virtual void init() = 0;
virtual bool work() = 0;
virtual void finish() = 0;
protected:
SharedBuffer *mInPipe;
SharedBuffer *mOutPipe;
};
Implementation :
void Stage::Process(void * aArg)
{
init();
while(work());
finish();
}
In my pipeline class I create each thread this way :
void Pipeline::Start()
{
assert(mStages.size() > 0);
for (size_t i = 0; i < mStages.size(); ++i)
{
tthread::thread t1(&mStages[i].Process, 0); //C2276
}
}
I don't know if my design is flawed, I tried writing my own solution. My problem right now is that I can't seem to pass the function since it's a class member. It doesn't feel like it makes sense to me to have it as a static function since each Process call comes from a different sub-class of Stage.
Process is a class method - it's not a member of the class, so your syntax for referencing it is incorrect. Also, as a class method, it has to be called on an instance of the class - so you need a way to actually do that.
Thankfully, it looks like the library allows you to pass in a context argument - which in your case should be your Stage*. So all you need to do is create a function matching the signature that the library expects that will do the right thing:
void CallProcess(void* stage) {
static_cast<Stage*>(stage)->Process();
}
And pass that in:
tthread::thread t1(CallProcess , &mStages[i]);
// void(*)(void*), void*
Note that in C++11, we can actually create a thread to call Process directly:
std::thread t1(&Stage::Process, mStages[i]);

Reconciling classes, inheritance, and C callbacks

In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I chose to create an abstract base class which would uniformly handle a given selection of libraries.
Consider this simplification of my design:
class BaseClass
{
public:
BaseClass() {}
~BaseClass() {}
bool init() { return doInit(); }
bool run() { return doWork(); }
void shutdown() { destroy(); }
private:
virtual bool doInit() = 0;
virtual bool doWork() = 0;
virtual void destroy() = 0;
};
And a class that inherits from it:
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass()
: BaseClass(), state_manager(new SomeOtherClass()) {}
int callbackA(int a, int b);
private:
virtual bool doInit();
virtual bool doWork();
virtual void destroy();
SomeOtherClass* state_manager;
};
// LSC.cpp:
bool LibrarySupportClass::doInit()
{
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&LibrarySupportClass::callbackA);
return true;
}
// ... and so on
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks. I would prefer doing all of these callbacks within the class because the class carries a state object.
What I ended up doing is...
static LibrarySupportClass* _inst_ptr = NULL;
static int callbackADispatch(int a, int b)
{
_inst_ptr->callbackA(a, b);
}
bool LibrarySupportClass::doInit()
{
_inst_ptr = this;
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&callbackADispatch);
return true;
}
This will clearly do Bad Things(TM) if LibrarySupportClass is instantiated more than once, so I considered using the singleton design, but for this one reason, I can't justify that choice.
Is there a better way?
You can justify that choice: your justification is that the C library only supports one callback instance.
Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach.
Here's how I'd do it.
LibrarySupportClass.h
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass();
~LibrarySupportClass();
static int static_callbackA(int a, int b);
int callbackA(int a, int b);
private:
//copy and assignment are rivate and not implemented
LibrarySupportClass(const LibrarySupportClass&);
LibrarySupportClass& operator=(const LibrarySupportClass&);
private:
static LibrarySupportClass* singleton_instance;
};
LibrarySupportClass.cpp
LibrarySupportClass* LibrarySupportClass::singleton_instance = 0;
int LibrarySupportClass::static_callbackA(int a, int b)
{
if (!singleton_instance)
{
WHAT? unexpected callback while no instance exists
}
else
{
return singleton_instance->callback(a, b);
}
}
LibrarySupportClass::LibrarySupportClass()
{
if (singleton_instance)
{
WHAT? unexpected creation of a second concurrent instance
throw some kind of exception here
}
singleton_instance = this;
}
LibrarySupportClass::~LibrarySupportClass()
{
singleton_instance = 0;
}
My point is that you don't need to give it the external interface of a canonical 'singleton' (which e.g. makes it difficult to destroy).
Instead, the fact that there is only one of it can be a private implementation detail, and enforced by a private implementation detail (e.g. by the throw statement in the constructor) ... assuming that the application code is already such that it will not try to create more than one instance of this class.
Having an API like this (instead of the more canonical 'singleton' API) means that you can for example create an instance of this class on the stack if you want to (provided you don't try to create more than one of it).
The external constraint of the c library dictates that when your callback is called you don't have the identification of the "owning" instance of the callback. Therefore I think that your approach is correct.
I would suggest to declare the callbackDispatch method a static member of the class, and make the class itself a singleton (there are lots of examples of how to implement a singleton). This will let you implement similar classes for other libraries.
Dani beat me to the answer, but one other idea is that you could have a messaging system where the call back function dispatch the results to all or some of the instances of your class. If there isn't a clean way to figure out which instance is supposed to get the results, then just let the ones that don't need it ignore the results.
Of course this has the problem of performance if you have a lot of instances, and you have to iterate through the entire list.
The problem the way I see it is that because your method is not static, you can very easily end up having an internal state in a function that isn't supposed to have one, which, because there's a single instance on the top of the file, can be carried over between invocations, which is a -really- bad thing (tm). At the very least, as Dani suggested above, whatever methods you're calling from inside your C callback would have to be static so that you guarantee no residual state is left from an invocation of your callback.
The above assumes you have static LibrarySupportClass* _inst_ptr declared at the very top. As an alternative, consider having a factory function which will create working copies of your LibrarySupportClass on demand from a pool. These copies can then return to the pool after you're done with them and be recycled, so that you don't go around creating an instance every time you need that functionality.
This way you can have your objects keep state during a single callback invocation, since there's going to be a clear point where your instance is released and gets a green light to be reused. You will also be in a much better position for a multi-threaded environment, in which case each thread gets its own LibrarySupportClass instance.
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks
Can you elaborate? Is choosing a callback type based on userdata a problem?
Could your callback choose an instance based on a and/or b? If so, then register your library support classes in a global/static map and then have callbackADispatch() look up the correct instance in the map.
Serializing access to the map with a mutex would be a reasonable way to make this thread-safe, but beware: if the library holds any locks when it invokes your callback, then you may have to do something more clever to avoid deadlocks, depending on your lock hierarchy.