Kigs Framework Introduction (6/8) - Signal, Slot, Notification

 
Rate me!
0.00 (No votes)
 
26 Feb 2020MIT
A multi purpose, cross-platform, free and Open Source C++ framework. This article will focus on Signal/Slot and Notification mechanisms.
This short article demonstrates the use of Signals, Slots and Notifications in the Kigs framework. Signals, Slots and Notifications are used to communicate between instances.

Kigs Logo

Table of Contents

Introduction

Now that we have seen how CoreModifiable methods (Kigs Framework Introduction (4/8) - Methods) works, we are going to see in this short article how to take advantage of this mechanism to easily connect instances together.

Signals and Slots

Signals

A list of signals can be declared at compile time for a given class using helper macro SIGNALS:

// CoreModifiable signals 
SIGNALS(PreInit, 
	PostInit,
	Uninit,
	Destroy,
	Update, // Called before the actual update
	NotifyUpdate,
	AddItem,
	RemoveItem,
	PrepareExport,
	EndExport);

It is then possible to retrieve the list of declared signals for this class using method "GetSignalList" :

// get the list of SimpleClass signals
std::cout << "simpleclass instance has following signals available" << std::endl;
auto signallist=simpleclass->GetSignalList();
for (const auto& s : signallist)
{
#ifdef KEEP_NAME_AS_STRING
	std::cout << s._id_name << std::endl;
#else
	std::cout << s._id << std::endl;
#endif
}

Slots and Connections

A declared signal can be emitted using EmitSignal method:

// emit signal with two parameters
EmitSignal(Signals::SendSignal1,32,64);

It's also possible with the same mechanism to send undeclared signals:

// emit a "runtime" signal (not declared with the SIGNALS macro) 
EmitSignal("doSomething");

Signals can be emitted with or without parameters.

For an instance to receive a signal from another one, a connection must be setup :

// connect this "MethodWithParams" to simpleclass instance "SendSignal1" signal
KigsCore::Connect(simpleclass.get(),"SendSignal1",this, "MethodWithParams");
// connect app undeclared doSomething signal to doSomething method
KigsCore::Connect(app, "doSomething", this, "doSomething");

"MethodWithParams" is a CoreModifiable method declared with WRAP_METHODS macro or with DECLARE_METHOD/COREMODIFIABLE_METHODS. See CoreModifiable method article in this series for details.

// Wrapped MethodWithParams
void	MethodWithParams(float p1, float p2);
WRAP_METHODS(MethodWithParams);
// fixed prototype CoreModifiable method
DECLARE_METHOD(doSomething);
// list methods
COREMODIFIABLE_METHODS(doSomething);

To disconnect two instances, KigsCore::Disconnect method is also available :

// disconnect this so SendSignal1 will not be catched anymore
CoreModifiable* simplecass=GetInstanceByPath("simpleclass");
KigsCore::Disconnect(simplecass, "SendSignal1", this, "MethodWithParams");

Lambda Slots

It's also possible to connect signal to a lambda function directly:

// connect to lambda function
KigsCore::Connect(simpleclass.get(), "SendSignal2", this, "lambda", [this](int p1)
{
	std::cout << "lambda received parameter " << p1 << std::endl;
});

Instance Factory Connection

It's possible to ask instance factory to create a connection for each created instance of a particular class:

// ask instance factory to add a connection on each created SimpleClass 
// for the PreInit signal to call this OnSimpleClassPreInit
KigsCore::Instance()->GetInstanceFactory()->addModifiableCallback
                      ("PreInit", this, "OnSimpleClassPreInit", "SimpleClass");

If the last parameter is not set, the connection is added for all types of created instances.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

To remove the automatic connection:

// remove instance factory auto connection previously set
KigsCore::Instance()->GetInstanceFactory()->removeModifiableCallback
                      ("PreInit", this, "OnSimpleClassPreInit");

Notifications

Another way to create connections is to use the NotificationCenter class. NotificationCenter can connect two instances like with signal/slot mechanism, but also notify an instance to listen for notification posted by any sender instance.

Observers

The NotificationCenter can register observer instances:

// register this as an observer on notification "doSomethingElseNotif" 
// call method CatchNotifMethod when doSomethingElseNotif is received
KigsCore::GetNotificationCenter()->addObserver(this,"CatchNotifMethod","doSomethingElseNotif");

A fourth CoreModifiable* parameter is possible to listen to notifications only coming from the given sender instance.

To remove an observer:

// remove this as "doSomethingElseNotif" notification observer. 
// a third parameter is needed if observer was set on a specific instance.
KigsCore::GetNotificationCenter()->removeObserver(this, "doSomethingElseNotif");

Post a Notification

A notification can then be sent using NotificationCenter "postNotificationName" method:

// post a notification "doSomethingElseNotif" 
// a vector of CoreModifiable attributes can be set as second parameter : 
// kstl::vector<CoreModifiableAttribute*>& params
// the sender can also be passed (as second or third parameter)
KigsCore::GetNotificationCenter()->postNotificationName("doSomethingElseNotif", this);

Serialization

A signal/slot connection can be set in XML adding this kind of item to an instance:

<Connect Si="SignalName" E="EmitterPath" SL="SlotName" R="ReceiverPath"/>

Emitter path and receiver path are classic CoreModifiable search paths. "this" or "self" can also be used to indicate owning instance.

An observer can also be set on an instance adding this item:

<OnE N="NotificationName" A="CalledMethod"/>

Find all the sample code from this wiki section in Sample6 project (browse the code).

Already Published in this Series

  1. Kigs Framework Introduction (1/8) - Overview
  2. Kigs Framework Introduction (2/8) - CoreModifiable
  3. Kigs Framework Introduction (3/8) - Attributes
  4. Kigs Framework Introduction (4/8) - Methods
  5. Kigs Framework Introduction (5/8) - CoreItem
  6. Kigs Framework Introduction (6/8) - Signal, Slot, Notification

History

  • 26th February, 2020: Initial version

[출처] https://www.codeproject.com/Articles/5260113/Kigs-Framework-Introduction-6-8-Signal-Slot-Notifi

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
23 [C/C++ 인공지능] Artificial Neural Network C++ Class : 인공신경망 C++ 클래스 file 졸리운_곰 2023.11.25 308
22 [C/C++ 인공지능] Visual Studio 2019에서 LibTorch 사용하기 file 졸리운_곰 2023.11.20 392
21 [C/C++ 인공지능] A Simple and Complete Explanation of Neural Networks : 신경망에 대한 간단하고 완전한 설명 file 졸리운_곰 2023.10.22 279
20 [C/C++ 인공지능] Deep Learning from Scratch in C++: Tensor Programming file 졸리운_곰 2023.09.06 340
19 [C/C++ 인공지능] Getting Started with mlpack 졸리운_곰 2023.01.28 310
18 [C/C++][인공지능] Most Useful C/C++ ML Libraries Every Data Scientist Should Know file 졸리운_곰 2022.10.01 423
17 [인공지능] 추론 기법 file 졸리운_곰 2022.05.05 509
16 [C++ 인공지능] C ++을 이용한 단순 MLP 역 전파 인공 신경망 (단계 별) file 졸리운_곰 2022.04.11 370
15 [C/C++인공지능] An Introduction to Machine Learning Libraries for C++ file 졸리운_곰 2021.12.06 360
14 [C/C++][tensorflow 1.x] windows C lib : [Tensorflow] How to Install Tensorflow for C API file 졸리운_곰 2021.11.19 396
13 [C/C++][tensorflow] tensorflovw 1.x version 텐서플로우 C 예제 file 졸리운_곰 2021.11.19 544
12 [C/C++ 인공지능][linux][cuda] flashlight file 졸리운_곰 2021.11.09 506
11 [C/C++] (고전 기호 처리 인공지능) 전문가 시스템 file 졸리운_곰 2020.06.13 330
10 [유전알고리즘] 자동 그림생성 프로그램 - Evolving Image file 졸리운_곰 2018.03.04 910
9 대화 프로그램 - ELIZA 졸리운_곰 2018.03.04 360
8 Caffe 설치하기 ๑•‿•๑ (2) file 졸리운_곰 2018.02.21 337
7 Caffe 설치하기 ๑•‿•๑ (1) file 졸리운_곰 2018.02.21 427
6 Windows 에 Caffe 설치하기 (๑•‿•๑) 졸리운_곰 2018.02.21 306
5 Windows에서 Caffe 예제 돌리기 : MNIST(1) (๑•‿•๑) file 졸리운_곰 2018.02.21 356
4 Caffe 구성 요소들 알아보기: blobs, nets, layer, solver, prototxt ๑•‿•๑ file 졸리운_곰 2018.02.21 569
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED