Kigs Framework Introduction (4/8) - Methods

 
Rate me!
5.00 (3 votes)
 
13 Feb 2020MIT
A multi purpose, cross-platform, free and Open Source C++ framework. This article will focus on CoreModifiable methods.
This article demonstrates the use of CoreModifiable methods - how to declare them, how to define them and how to call them. CoreModifiable methods are an important mechanism used by signal / slot management and notification among others.

Kigs Logo

Table of Contents

Introduction

Check Already Published in this Series section to know what was seen before.

In this article, we will focus on CoreModifiable methods. CoreModifiable methods are methods that can be called by their name without knowing the exact type of the called instance.

Fast Access Fixed Prototype Methods

Fixed prototype is:

bool    methodName(CoreModifiable* sender,
        kstl::vector<CoreModifiableAttribute*>& params,void* privateParams);

Parameters are:

  • CoreModifiable* sender: caller class
  • kstl::vector<CoreModifiableAttribute*>& paramsvector of CoreModifiableAttribute* parameters
  • void* privateParams: a possible user defined private param

Return value is a bool value. Meaning of the return value is user defined.

Helper macros can be used to declare a member method: DECLARE_METHODDECLARE_VIRTUAL_METHODDECLARE_PURE_VIRTUAL_METHOD.

// declare member method called "GiveInfos"
DECLARE_METHOD(GiveInfos);

Helper macro DEFINE_METHOD is then used to define method:

// define member method named GiveInfos on SimpleClass
DEFINE_METHOD(SimpleClass, GiveInfos)
{
    
    std::cout << "SimpleClass GiveInfos method called on 
                 " << getName() << " instance" << std::endl;
    std::cout << "-- sender : " << sender->getName() << std::endl;

    for (auto p : params)
    {
#ifdef KEEP_NAME_AS_STRING
        std::string v;
        if (p->getValue(v))
        {
            std::cout << "-- parameter : " << p->getID()._id_name << 
                         " value is : " << v << std::endl;
        }
        else
        {
            std::cout << "-- parameter : " << p->getID()._id_name << 
                         " value cannot be evaluated as string" << std::endl;
        }
#else
        std::string v;
        if (p->getValue(v))
        {
            std::cout << "-- parameter : " << p->getID()._id << 
                         " value is : " << v << std::endl;
        }
        else
        {
            std::cout << "-- parameter : " << p->getID()._id << 
                         " value cannot be evaluated as string" << std::endl;
        }
#endif
    }

    if(privateParams)
        std::cout << "-- private parameter is not null" << std::endl;
    else
        std::cout << "-- private parameter is null" << std::endl;

    return true;
}

Fast Call

Then method can be called with "CallMethod" like this:

// create dynamic attribute on this
AddDynamicAttribute<maFloat, float>("FloatParam", 12.0f);

// create CoreModifiableAttribute without owner
CoreModifiableAttribute* intParam = new maInt("IntParam", 15);

// create a parameter vector
std::vector<CoreModifiableAttribute*> params;
// push dynamic attribute "FloatParam" on vector
params.push_back(getAttribute("FloatParam"));
// push intParam
params.push_back(intParam);
    
// call GiveInfos on instance1 with params vector, no private parameter, and sender is this  
bool result = instance1->CallMethod("GiveInfos", params, nullptr, this);
std::cout << "GiveInfos returns " << (result?"true":"false") << std::endl << std::endl;

// call GiveInfos on instance1 with this instance (Sample4) as parameter, 
// no private params and no sender
// so the received parameter vector will be all the CoreModifiable attributes owned by this
result = instance1->CallMethod("GiveInfos", this, nullptr, nullptr);
std::cout << "GiveInfos returns " << (result ? "true" : "false") << std::endl << std::endl;

Slower Simple Call

The SimpleCall template method automatically encodes parameters in vector:

// "SimpleCall" on instance2:
result = instance2->SimpleCall("GiveInfos", 32,64,5);
std::cout << "GiveInfos returns " << (result ? "true" : "false") << std::endl << std::endl;

Returned Value

Returned value can be pushed on parameter vector with helper macro PUSH_RETURN_VALUE.
When called using CallMethod, the returned value and allocated parameters must be deleted after the call (or a memory leaks will occur).

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

// call GiveInfos on instance2 with params vector, no private parameter and sender is this  
int paramsCount = params.size();
result = instance2->CallMethod("GiveInfos", params, nullptr, this);
if (params.size() > paramsCount)
{
    // return values added
    while(paramsCount<params.size())
    {
        std::string v;
        if(params.back()->getValue(v))
            std::cout << "GiveInfos returned value = " << v << std::endl;

        delete params.back();
        params.pop_back();
    }
}
std::cout << "GiveInfos returns " << (result ? "true" : "false") << std::endl << std::endl;

With SimpleCall, the returned value can be managed automatically with template parameter:

// "SimpleCall" on instance2:
float floatresult = instance2->SimpleCall<float>("GiveInfos", 32,64,5);
std::cout << "GiveInfos returns " << floatresult << std::endl << std::endl;

Slower Access Wrapped Methods

Any member method can be wrapped as a CoreModifiable method. In class declaration:

float Multiply(float v1, float v2)
{
    return v1 * v2;
}
// Multiply method can be called with SimpleCall
WRAP_METHODS(Multiply);

Then Multiply method can be called like this:

float floatresult = instance2->SimpleCall<float>("Multiply", 32, 5);
std::cout << "instance2 Multiply returns " << floatresult << std::endl << std::endl;

Dynamic Methods

CoreModifiable inherited instances can be enhanced with dynamic method.

A dynamic method can be defined like this:

// declare a dynamic method named addValues which can be added to any CoreModifiable instance
DEFINE_DYNAMIC_METHOD(CoreModifiable, addValues)
{
    float result = 0.0f;
    for (auto p : params)
    {
        float v;
        if (p->getValue(v))
        {
            result += v;
        }
    }
    PUSH_RETURN_VALUE(result);
    return true;
}

Then at run time, add this method to a given instance, and call it with SimpleCall:

// now add addValues method on instance2, calling name is also addValues
instance2->INSERT_DYNAMIC_METHOD(addValues, addValues);
floatresult = instance2->SimpleCall<float>("addValues", 32, 5);
std::cout << "instance2 addValues returns " << floatresult << std::endl << std::endl;

This mechanism can be used to decorate instances with a specific behaviour.

Find all the sample code from this article in Sample4 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

History

  • 13th February, 2020: Initial version
  • 21st February, 2020: Article (5/8) added to the series

[출처] https://www.codeproject.com/Articles/5257418/Kigs-framework-introduction-4-8-Methods

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
154 Windows 10에 한국어 입출력이 가능한 리눅스 데스크톱 설치하기 file 졸리운_곰 2020.06.29 289
153 [C/C++] (고전 기호 처리 인공지능) 전문가 시스템 file 졸리운_곰 2020.06.13 330
152 리눅스 파일 찾기 (파일 및 디렉토리 검색) file 졸리운_곰 2020.05.12 277
151 linux desktop 화면 해상도 변경 file 졸리운_곰 2020.04.09 270
150 Kigs Framework Introduction (7/8) - Lua Binding 졸리운_곰 2020.03.23 337
149 crontab 저장 파일 위치 졸리운_곰 2020.03.02 321
148 crontab 백업 방법 스크립트 졸리운_곰 2020.03.02 285
147 리눅스 우분투 crontab (크론탭) 설정 졸리운_곰 2020.03.02 281
146 Kigs Framework Introduction (6/8) - Signal, Slot, Notification file 졸리운_곰 2020.02.28 321
145 Kigs Framework Introduction (5/8) - CoreItem file 졸리운_곰 2020.02.28 322
» Kigs Framework Introduction (4/8) - Methods file 졸리운_곰 2020.02.28 278
143 Kigs Framework Introduction (3/8) - Attributes file 졸리운_곰 2020.02.28 219
142 Kigs Framework Introduction (2/8) - CoreModifiable file 졸리운_곰 2020.02.28 258
141 Kigs Framework Introduction (1/8) file 졸리운_곰 2020.02.27 265
140 wxwidgets 과 codeblock 설치(리눅스) 졸리운_곰 2019.12.25 228
139 [windows] MinGW, wxWidget, Code:Blocks를 이용한 C/C++ IDE 환경 구축 file 졸리운_곰 2019.12.25 480
138 ubuntu 18.04.2 LTS 개발환경 세팅 졸리운_곰 2019.12.25 223
137 꼭 필요한 리눅스 명령어, file 졸리운_곰 2019.10.15 411
136 [Ubuntu 18.04] 원격 데스크톱 file 졸리운_곰 2019.02.23 331
135 Tasksel – Easily and Quickly Install Group Softwares in Debian and Ubuntu file 졸리운_곰 2018.10.14 296
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED