SlideShare a Scribd company logo
1 of 40
Download to read offline
1
A simple and powerful
property system for C++
GCDC 2008
David Salz
david.salz@bitfield.de
2
• Bitfield
• small studio from Berlin, Germany
• founded in 2006
• developer for PC, DS, Wii
• focus on casual games for PC and DS
• advertising games for trade shows &
events
3
• Bitfield
• licensed DS middleware developer
• BitEngineDS, high level game engine
• used in 10 games so far
• adventure, jump‘n‘run, puzzle games, pet
simulation
• www.bitfield.de
4
• Games Academy
• founded in 2000
• based in Berlin and
Frankfurt/Main
• ~170 students
• Hire our students!
• Constantly looking for
teachers and
lecturers!
5
What is a Property System?
class CCar
{
Vec3 position;
DWORD color
float max_speed;
int ai_type;
...
* 3d model
* shader parameters
* sounds
etc.
...
};
location 127.3, 0, 14.0
max speed 120 km/h
color
AI Type Easy
Team 2
▼
▼
▲
...
3d model mini.x ...
6
Uses of Property Systems (1)
• a property system can be used for a lot of things!
• serialization
• store objects on disc (or stream over network)
• e.g. saved games, level file format, scene graph file format
• undo / redo
• figure out which properties were changed, store old value
• = selective serialization
• client / server synchronization
• send changed properties to client/server
• = selective serialization
7
Uses of Property Systems (2)
• a property system can be used for a lot of things!
• animation
• change property values over time
• e.g. animated GUIs, in-game cut-scenes
• integration of scripting languages
• automatically create „glue code“ to access object
properties from scripting languages
8
What do we want? (1)
• easy-to-use system
• lightweight
• cause as little performance and memory overhead as possible
• performance may not be an issue for editors...
• ...but may for serialization, animation, scripting languages
• type safe
• i.e. all C++ type safety and type conversion mechanisms should stay
intact
• non-intrusive
• i.e. it should not require modification of the class whose properties
are to be exposed
• it might by part of an external library; source code may not be available
9
What do we want? (2)
• support polymorphic objects
• i.e. work correctly with virtual functions
• be aware of C++ protection mechanisms
• i.e. not violate const, private or protected modifiers
• support real-time manipulation of objects with no
extra code
• i.e. the object should not need extra code to deal with a changed
property at runtime
10
Existing Solutions
• ... using data pointers
• ... using strings
• … using databases
• ... using reflection
• properties in Microsoft .NET
• ... using member function pointers
11
Data Pointers (1)
• „A Property Class for Generic C++ Member
Access“
• by Charles Cafrelli, published in Game Programming
Gems 2
• Idea:
• store a pointer to the data (inside to object)
• plus type information
• plus name
12
Data Pointers (2)
class Property
{
protected:
union Data
{
int* m_int;
float* m_float;
string* m_string;
bool* m_bool;
};
enum Type
{
INT,
FLOAT,
STRING,
BOOL,
EMPTY
};
Data m_data;
Type m_type;
string m_name;
Property(string const& name, int* value);
Property(string const& name, float* value);
Property(string const& name, string* value);
Property(string const& name, bool* value);
~Property ();
bool SetUnknownValue(string const& value);
bool Set(int value);
bool Set(float value);
bool Set(string const& value);
bool Set(bool value);
void SetName(string const& name);
string GetName() const;
int Getlnt();
float GetFloatf);
string GetString();
bool GetBool();
}
13
Data Pointers (3)
class PropertySet
{
protected:
HashTable<Property>m_properties;
public:
PropertySet();
virtual -PropertySet();
void Register(string const& name, int* value);
void Register(string const& name, float* value);
void Register(string const& name, string* value);
void Register(string const& name, bool* value);
// look up a property
Property* Lookup(string const& name);
// get a list of available properties
bool SetValue(string const& name, string* value);
bool Set(string const& name, string const& value);
bool Set(string const& name, int value);
bool Set(string const& name, float value);
bool Set(string const& name, bool value);
bool Set(string const& name, char* value);
};
class GameObj : public PropertySet
{
int m_test;
GameObj()
{
Register("test",&m_test);
}
};
Property* testprop =
aGameObj->Lookup("test");
int test_value =
testprop->GetInt();
14
Data Pointers (4)
• Problems:
• Is it a good idea to modify a (private?) variable
directly?
•  need to notify object after property change!
• objects carry unnecessary and redundant data
• every GameObj holds string names for all properties...
• ... and pointers to it’s own members!
• support for more types?
• could be done using templates
• or by storing data as string internally
15
String-Based Properties
• Idea:
• store all properties as strings
• convert from / to string as needed
• used by CEGui
• Crazy Eddie's GUI System; open source GUI
• used with OGRE / Irrlicht game engines
• used in several commercial games
16
17
• PropertyReceiver is just an empty class, used for type safety
• there is a derived class for every property of every class (181 !)
CEGUI::Property
d_name : String
d_help : String
d_default : String
d_writeXML : bool
get(const PropertyReceiver*) : String
set(PropertyReceiver*, const String&)
writeXMLToStream (const PropertyReceiver *,
XMLSerializer&)
CEGUI::PropertyReceiver
ConcreteProperty
ConcreteWidget
CEGUI::PropertyDefinitionBase
writeCausesRedraw : bool
writeCausesLayout : bool
p : ConcretePropery {static}
*
18
• concrete property...
• ... converts string from / to correct type
• ... casts receiver to correct target type
• ... goes trough public API
class Selected : public Property
{
public:
Selected() : Property("Selected", "Property to get/set the selected state
of the Checkbox. Value is either "True" or "False".", "False") {}
String get(const PropertyReceiver* receiver) const
{
return PropertyHelper::boolToString(
static_cast<const Checkbox*>(receiver)->isSelected());
}
void set(PropertyReceiver* receiver, const String& value)
{
static_cast<Checkbox*>(receiver)->setSelected(
PropertyHelper::stringToBool(value));
}
}
19
• PropertySet holds a list of properties
• every Widget is a PropertySet; adds its own properties to the list
ConcreteWidget
p : ConcretePropery {static}
CEGUI::PropertyReceiverCEGUI::PropertySet
void addProperty (Property *property)
getProperty (String &name) : String
setProperty (String &name, String &value)
CEGUI::Property
ConcreteProperty
*
*
20
String-Based Properties
• Problems:
• a lot of hand-written glue code
• inefficient string conversions for every access
• Pros:
• strings can be used for XML serialization
• property data held per class, not per instance
• goes through public interface of the class
• class can react to changes properly
21
Databases
• Idea:
• store all properties in a database (SQL / XML /
whatever)
• database API is single point of access for everything
• obvious for Browser / Online games
• Extreme: „There is no game entity class!“
• But:
• There is always some code representation of the data
• May not be feasable for small devices
• Speed / memory footprint?
22
Reflection (1)
• reflection
• ability of a program to observe its internal structure at
runtime
• assembly code in memory can be read and interpreted
• some scripting languages treat source code as strings
• typically on a high level
• figure out type of an object at runtime (introspection;
polymorphism)
• get the class name as a string
• get method names as strings
• figure out parameters and return types of methods
• supported by Objective C, Java, C#, VB .Net,
Managed C++
23
Reflection (2)
• how does it work?
• meta data generated by compiler
• special interfaces to query type info from objects (=
virtual functions)
• lots of string lookups at runtime
// trying to call: String FooNamespace.Foo.bar()
Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo");
MethodInfo methodInfo = obj.GetType().GetMethod("bar");
// invoke the method, supplying parameter array with 0 size
value = (String)methodInfo.Invoke(obj, new Object[0]);
C#
24
Reflection (3)
• Why doesn‘t C++ support this?
• no single-rooted hierarchy
• no common „Object“ base class for everything
• void* is most “compatible” type
• primitive types not really integrated into OO structure
• Java and .NET have wrapper classes for them
• .NET: “boxing” / “unboxing” mechanism
• C++ supports early and late binding
• i.e. supports non-virtual functions
• ... and classed without a VTable
• RTTI works for objects with VTable only
• VTable is not generated just for RTTI
25
Reflection (4)
• Reflection Libraries for C++ (just examples)
• Seal Reflex
• by European Organization for Nuclear Research (CERN)
• uses external tool (based on ) GCCXML) to parse C++ code and
generate reflection info
• non-intrusive; generates external dictionary for code
• up to date; supports latest gcc and VisualC++
• can add own meta-info to code (key-value-pairs)
• http://seal-reflex.web.cern.ch
Type t = Type::ByName("MyClass");
void * v = t.Allocate(); t.Destruct(v);
Object o = t.Construct();
for (Member_Iterator mi = t.Member_Begin(); mi != t.Member_End(); ++mi)
{
switch ((*mi).MemberType())
{
case DATAMEMBER : cout << "Datamember: " << (*mi).Name() << endl;
case FUNCTIONMEMBER : cout << "Functionmember: " << (*mi).Name() << endl;
}
}
26
Reflection (5)
• Reflection Libraries for C++ (just examples)
• CppReflection
• by Konstantin Knizhnik
• reflection info supplied partly by programmer (through macros)
• ... and partly taken from debug info generated by compiler
• http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html
class A
{
public:
int i;
protected:
long larr[10];
A** ppa;
public:
RTTI_DESCRIBE_STRUCT((RTTI_FIELD(i, RTTI_FLD_PUBLIC),
RTTI_ARRAY(larr, RTTI_FLD_PROTECTED),
RTTI_PTR_TO_PTR(ppa, RTTI_FLD_PROTECTED)));
};
27
Reflection (5)
• Boost Reflection
• by Jeremy Pack
• not part of the boost libraries yet!
• programmer must specify reflection info (through
macros / templates)
• http://boost-extension.blogspot.com
• also possible: COM and CORBA
• APIs that provide communication across language
boundaries
• also contain type description facilities
28
.NET Property System (1)
class CTestClass
{
private int iSomeValue;
public int SomeValue
{
get() { return iSomeValue; }
set() { iSomeValue = value; }
}
}
C#
CTestClass pTestClass = new CTestClass();
pTestClass.SomeValue = 42; // implicitly calls set()
System.Console.WriteLn(pTestClass.SomeValue); // implicitly calls get()
C#
• properties in .NET languages
• ... look like member variables to the outside
• ... but really are functions!
•  syntactic alternative to get/set functions
29
.NET Property System (2)
• just syntactic sugar?
ref class CTestClass
{
private:
int iSomeValue;
public:
property int SomeValue
{
int get() { return iSomeValue; }
void set(int value) { iSomeValue = value; }
}
}
Managed C++
CTestClass^ pTestClass = gcnew CTestClass;
pTestClass->SomeValue = 42;
System::Console::WriteLn(pTestClass->SomeValue);
Managed C++
30
.NET Property System (3)
• clean alternative to get/set methods
• look like one data field from the outside
• can still allow only get or only set
• can be abstract, inherited, overwritten, work with polymorphism
• interesting in connection with reflection
• reflection can tell difference between a „property“ and normal
methods
• can add custom attributes to properties
• through System.Attribute class
• e.g. description text, author name... anything you want
31
PropertyGrid control displays and
manipulates properties of any Object
using reflection.
32
property names
named property groups
description text for each property
custom editing controls
for different property types
validity criteria,
e.g. minimum/maximum value,
list of valid values
lists of predefined values
(but some of that
is domain knowledge the
editor has and not part
or the property system
33
• windows forms editor clearly using domain knowledge
to display special controls for some properties
• can figure out the names of the enum entries using refelection,
but not what „top“ or „fill“ means
public enum class DockStyle
{
Bottom,
Fill,
Left,
None,
Right,
Top
}
[LocalizableAttribute(true)]
public: virtual property DockStyle Dock
{
DockStyle get ();
void set (DockStyle value);
}
34
Homebrew Properties!
• accessing properties through functions  good idea!
• clean: uses public API
• object can react to changes
• hides implementation from outside
• Idea 1:
• use member function pointers
• i.e. existing get/set functions
• Idea 2:
• decouple per-instance and per-class data
• type information needs to be kept only once per class!
35
CGenericProperty
pUserObj : void*
pDescription: CGenericPropertyDescription*
GetTypeId() : type_info&;
GetName() : string;
GetDescriptionText() : string;
GetSemantic() : string;
GetDescription() : string;
GetReadOnly() : string;
CGenericPropertyDescription
LoadFromString(void* pObject, const string& rsString)
SaveToString(const void* pObject, string& rsString)
m_sName : std::string;
m_pType : const type_info*;
m_sDesciptionText : std::string;
m_bReadOnly : bool;
m_sSemantic : std::string;
per instance data:
- client object
- pointer to description
= 8 bytes
per class data
size does not really matter
property fetches most info
from here
36
• CProperty does not add any data members!
• can create array of CGenericProperty values and
cast them as needed
• not using polymorphism
CGenericProperty
pUserObj : void*
pDescription: CGenericPropertyDescription*
CProperty
SetValue(T)
GetValue() : T
T : typename
37
CGenericPropertyDescription
name, type, description, semantic...
CGenericProperty
GetValue(const void* pObject) : T
SetValue(void* pObject, T xValue)
CPropertyDescriptionScalar
void (USERCLASS::*m_fpSetFunction)(T);
T (USERCLASS::*m_fpGetFunction)() const;
T m_xDefaultValue;
T m_xMinValue;
T m_xMaxValue;
T : typename
USERCLASS: typename
T : typename
CPropertyDescriptionEnum
void (USERCLASS::*m_fpSetFunction)(int);
int (USERCLASS::*m_fpGetFunction)() const;
int m_iDefaultValue;
std::vector<string> m_asPossibleValues;
USERCLASS: typename
works for:
char, short, long, float, double
Vec2, Vec3
contains enum values as
strings
38
CPropertyDescriptionString<CCheckBox, string> CCheckBox::Prop_Text(
"Text", "Text that appears next to CheckBox", false, "",
&CCheckBox::SetText, &CCheckBox::GetText);
CPropertyDescriptionEnum<CCheckBox> CCheckBox::Prop_State(
"State", "Current state", false, "Unchecked", "Unchecked Checked Default",
&CCheckBox::SetChecked, &CCheckBox::GetChecked);
void
CCheckBox::GetProperties(vector<CGenericProperty>& apxProperties) const
{
__super::GetProperties(apxProperties);
apxProperties.push_back(CGenericProperty(&Prop_Text, (void*) this));
apxProperties.push_back(CGenericProperty(&Prop_State, (void*) this));
}
class CCheckBox
{
enum CheckBoxState { CB_Unchecked, CB_Checked, CB_Default };
void SetChecked(int p_eChecked = CB_Checked);
int GetChecked() const;
void SetText(string sText);
string GetText() const;
void GetProperties(vector<CGenericProperty>& apxProperties) const;
};
39
Homebrew Properties!
• semantic
• gives editor a hint how property is used
• a string property could be...
• ... a file name
• ... a font name
• ... or just a string
• Validation / Range data
• Different for each type
• Scalar : min / max / default value
• Enum: list of named values, default value
• String: max length, allowed characters, default value
40
if you want the slides:
david.salz@bitfield.de
Questions / Comments?
Thank you!

More Related Content

What's hot

Making archive IL2C #6-55 dotnet600 2018
Making archive IL2C #6-55 dotnet600 2018Making archive IL2C #6-55 dotnet600 2018
Making archive IL2C #6-55 dotnet600 2018Kouji Matsui
 
전리품 분배 시스템 기획 배상욱
전리품 분배 시스템 기획 배상욱전리품 분배 시스템 기획 배상욱
전리품 분배 시스템 기획 배상욱SwooBae
 
The Guerrilla Guide to Game Code
The Guerrilla Guide to Game CodeThe Guerrilla Guide to Game Code
The Guerrilla Guide to Game CodeGuerrilla
 
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013영욱 오
 
<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서
<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서
<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서LEE JONGCHANG
 
게임 인공지능 설계
게임 인공지능 설계게임 인공지능 설계
게임 인공지능 설계ByungChun2
 
Game Project / Working with Unity
Game Project / Working with UnityGame Project / Working with Unity
Game Project / Working with UnityPetri Lankoski
 
Killzone Shadow Fall Demo Postmortem
Killzone Shadow Fall Demo PostmortemKillzone Shadow Fall Demo Postmortem
Killzone Shadow Fall Demo PostmortemGuerrilla
 
레벨 디자인의 구성
레벨 디자인의 구성레벨 디자인의 구성
레벨 디자인의 구성준태 김
 
윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018
윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018
윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018devCAT Studio, NEXON
 
Mobile AR Lecture6 - Introduction to Unity 3D
Mobile AR Lecture6 - Introduction to Unity 3DMobile AR Lecture6 - Introduction to Unity 3D
Mobile AR Lecture6 - Introduction to Unity 3DMark Billinghurst
 
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)David Salz
 
Game object models - Game Engine Architecture
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine ArchitectureShawn Presser
 
MMO Design Architecture by Andrew
MMO Design Architecture by AndrewMMO Design Architecture by Andrew
MMO Design Architecture by AndrewAgate Studio
 
전투 시스템 기획(Canvas 스터디 1차)
전투 시스템 기획(Canvas 스터디 1차)전투 시스템 기획(Canvas 스터디 1차)
전투 시스템 기획(Canvas 스터디 1차)Chanman Jo
 
Dynamic Wounds on Animated Characters in UE4
Dynamic Wounds on Animated Characters in UE4Dynamic Wounds on Animated Characters in UE4
Dynamic Wounds on Animated Characters in UE4Michał Kłoś
 
고대특강 게임 프로그래머의 소양
고대특강   게임 프로그래머의 소양고대특강   게임 프로그래머의 소양
고대특강 게임 프로그래머의 소양Jubok Kim
 
레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2
레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2
레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2Jun Hyuk Jung
 
[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들
[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들
[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들강 민우
 

What's hot (20)

Making archive IL2C #6-55 dotnet600 2018
Making archive IL2C #6-55 dotnet600 2018Making archive IL2C #6-55 dotnet600 2018
Making archive IL2C #6-55 dotnet600 2018
 
전리품 분배 시스템 기획 배상욱
전리품 분배 시스템 기획 배상욱전리품 분배 시스템 기획 배상욱
전리품 분배 시스템 기획 배상욱
 
Unity 3D, A game engine
Unity 3D, A game engineUnity 3D, A game engine
Unity 3D, A game engine
 
The Guerrilla Guide to Game Code
The Guerrilla Guide to Game CodeThe Guerrilla Guide to Game Code
The Guerrilla Guide to Game Code
 
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
게임에서 흔히 쓰이는 최적화 전략 by 엄윤섭 @ 지스타 컨퍼런스 2013
 
<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서
<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서
<쿠키런:오븐브레이크> 길드탐험 및 방랑박쥐상점 컨텐츠 역기획서
 
게임 인공지능 설계
게임 인공지능 설계게임 인공지능 설계
게임 인공지능 설계
 
Game Project / Working with Unity
Game Project / Working with UnityGame Project / Working with Unity
Game Project / Working with Unity
 
Killzone Shadow Fall Demo Postmortem
Killzone Shadow Fall Demo PostmortemKillzone Shadow Fall Demo Postmortem
Killzone Shadow Fall Demo Postmortem
 
레벨 디자인의 구성
레벨 디자인의 구성레벨 디자인의 구성
레벨 디자인의 구성
 
윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018
윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018
윤석주, 인하우스 웹 프레임워크 Jul8 제작기, NDC2018
 
Mobile AR Lecture6 - Introduction to Unity 3D
Mobile AR Lecture6 - Introduction to Unity 3DMobile AR Lecture6 - Introduction to Unity 3D
Mobile AR Lecture6 - Introduction to Unity 3D
 
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)
 
Game object models - Game Engine Architecture
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine Architecture
 
MMO Design Architecture by Andrew
MMO Design Architecture by AndrewMMO Design Architecture by Andrew
MMO Design Architecture by Andrew
 
전투 시스템 기획(Canvas 스터디 1차)
전투 시스템 기획(Canvas 스터디 1차)전투 시스템 기획(Canvas 스터디 1차)
전투 시스템 기획(Canvas 스터디 1차)
 
Dynamic Wounds on Animated Characters in UE4
Dynamic Wounds on Animated Characters in UE4Dynamic Wounds on Animated Characters in UE4
Dynamic Wounds on Animated Characters in UE4
 
고대특강 게임 프로그래머의 소양
고대특강   게임 프로그래머의 소양고대특강   게임 프로그래머의 소양
고대특강 게임 프로그래머의 소양
 
레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2
레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2
레벨기획 프론티어 온라인 '이름없는 동굴' 던전_v2
 
[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들
[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들
[IGC2018] 청강대 이득우 - 언리얼에디터확장을위해알아야할것들
 

Similar to A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)

Getting started with C++
Getting started with C++Getting started with C++
Getting started with C++Michael Redlich
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++Michael Redlich
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
COMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and SoliCOMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and SoliMark Billinghurst
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptvinu28455
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろうUnity Technologies Japan K.K.
 
Online java training ppt
Online java training pptOnline java training ppt
Online java training pptvibrantuser
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Dina Goldshtein
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 

Similar to A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig) (20)

Java
Java Java
Java
 
Getting started with C++
Getting started with C++Getting started with C++
Getting started with C++
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Java Advanced Features
Java Advanced FeaturesJava Advanced Features
Java Advanced Features
 
Dr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot netDr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot net
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
COMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and SoliCOMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and Soli
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Introduction_to_Java.ppt
Introduction_to_Java.pptIntroduction_to_Java.ppt
Introduction_to_Java.ppt
 
Online java training ppt
Online java training pptOnline java training ppt
Online java training ppt
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 

Recently uploaded

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 

Recently uploaded (20)

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 

A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)

  • 1. 1 A simple and powerful property system for C++ GCDC 2008 David Salz david.salz@bitfield.de
  • 2. 2 • Bitfield • small studio from Berlin, Germany • founded in 2006 • developer for PC, DS, Wii • focus on casual games for PC and DS • advertising games for trade shows & events
  • 3. 3 • Bitfield • licensed DS middleware developer • BitEngineDS, high level game engine • used in 10 games so far • adventure, jump‘n‘run, puzzle games, pet simulation • www.bitfield.de
  • 4. 4 • Games Academy • founded in 2000 • based in Berlin and Frankfurt/Main • ~170 students • Hire our students! • Constantly looking for teachers and lecturers!
  • 5. 5 What is a Property System? class CCar { Vec3 position; DWORD color float max_speed; int ai_type; ... * 3d model * shader parameters * sounds etc. ... }; location 127.3, 0, 14.0 max speed 120 km/h color AI Type Easy Team 2 ▼ ▼ ▲ ... 3d model mini.x ...
  • 6. 6 Uses of Property Systems (1) • a property system can be used for a lot of things! • serialization • store objects on disc (or stream over network) • e.g. saved games, level file format, scene graph file format • undo / redo • figure out which properties were changed, store old value • = selective serialization • client / server synchronization • send changed properties to client/server • = selective serialization
  • 7. 7 Uses of Property Systems (2) • a property system can be used for a lot of things! • animation • change property values over time • e.g. animated GUIs, in-game cut-scenes • integration of scripting languages • automatically create „glue code“ to access object properties from scripting languages
  • 8. 8 What do we want? (1) • easy-to-use system • lightweight • cause as little performance and memory overhead as possible • performance may not be an issue for editors... • ...but may for serialization, animation, scripting languages • type safe • i.e. all C++ type safety and type conversion mechanisms should stay intact • non-intrusive • i.e. it should not require modification of the class whose properties are to be exposed • it might by part of an external library; source code may not be available
  • 9. 9 What do we want? (2) • support polymorphic objects • i.e. work correctly with virtual functions • be aware of C++ protection mechanisms • i.e. not violate const, private or protected modifiers • support real-time manipulation of objects with no extra code • i.e. the object should not need extra code to deal with a changed property at runtime
  • 10. 10 Existing Solutions • ... using data pointers • ... using strings • … using databases • ... using reflection • properties in Microsoft .NET • ... using member function pointers
  • 11. 11 Data Pointers (1) • „A Property Class for Generic C++ Member Access“ • by Charles Cafrelli, published in Game Programming Gems 2 • Idea: • store a pointer to the data (inside to object) • plus type information • plus name
  • 12. 12 Data Pointers (2) class Property { protected: union Data { int* m_int; float* m_float; string* m_string; bool* m_bool; }; enum Type { INT, FLOAT, STRING, BOOL, EMPTY }; Data m_data; Type m_type; string m_name; Property(string const& name, int* value); Property(string const& name, float* value); Property(string const& name, string* value); Property(string const& name, bool* value); ~Property (); bool SetUnknownValue(string const& value); bool Set(int value); bool Set(float value); bool Set(string const& value); bool Set(bool value); void SetName(string const& name); string GetName() const; int Getlnt(); float GetFloatf); string GetString(); bool GetBool(); }
  • 13. 13 Data Pointers (3) class PropertySet { protected: HashTable<Property>m_properties; public: PropertySet(); virtual -PropertySet(); void Register(string const& name, int* value); void Register(string const& name, float* value); void Register(string const& name, string* value); void Register(string const& name, bool* value); // look up a property Property* Lookup(string const& name); // get a list of available properties bool SetValue(string const& name, string* value); bool Set(string const& name, string const& value); bool Set(string const& name, int value); bool Set(string const& name, float value); bool Set(string const& name, bool value); bool Set(string const& name, char* value); }; class GameObj : public PropertySet { int m_test; GameObj() { Register("test",&m_test); } }; Property* testprop = aGameObj->Lookup("test"); int test_value = testprop->GetInt();
  • 14. 14 Data Pointers (4) • Problems: • Is it a good idea to modify a (private?) variable directly? •  need to notify object after property change! • objects carry unnecessary and redundant data • every GameObj holds string names for all properties... • ... and pointers to it’s own members! • support for more types? • could be done using templates • or by storing data as string internally
  • 15. 15 String-Based Properties • Idea: • store all properties as strings • convert from / to string as needed • used by CEGui • Crazy Eddie's GUI System; open source GUI • used with OGRE / Irrlicht game engines • used in several commercial games
  • 16. 16
  • 17. 17 • PropertyReceiver is just an empty class, used for type safety • there is a derived class for every property of every class (181 !) CEGUI::Property d_name : String d_help : String d_default : String d_writeXML : bool get(const PropertyReceiver*) : String set(PropertyReceiver*, const String&) writeXMLToStream (const PropertyReceiver *, XMLSerializer&) CEGUI::PropertyReceiver ConcreteProperty ConcreteWidget CEGUI::PropertyDefinitionBase writeCausesRedraw : bool writeCausesLayout : bool p : ConcretePropery {static} *
  • 18. 18 • concrete property... • ... converts string from / to correct type • ... casts receiver to correct target type • ... goes trough public API class Selected : public Property { public: Selected() : Property("Selected", "Property to get/set the selected state of the Checkbox. Value is either "True" or "False".", "False") {} String get(const PropertyReceiver* receiver) const { return PropertyHelper::boolToString( static_cast<const Checkbox*>(receiver)->isSelected()); } void set(PropertyReceiver* receiver, const String& value) { static_cast<Checkbox*>(receiver)->setSelected( PropertyHelper::stringToBool(value)); } }
  • 19. 19 • PropertySet holds a list of properties • every Widget is a PropertySet; adds its own properties to the list ConcreteWidget p : ConcretePropery {static} CEGUI::PropertyReceiverCEGUI::PropertySet void addProperty (Property *property) getProperty (String &name) : String setProperty (String &name, String &value) CEGUI::Property ConcreteProperty * *
  • 20. 20 String-Based Properties • Problems: • a lot of hand-written glue code • inefficient string conversions for every access • Pros: • strings can be used for XML serialization • property data held per class, not per instance • goes through public interface of the class • class can react to changes properly
  • 21. 21 Databases • Idea: • store all properties in a database (SQL / XML / whatever) • database API is single point of access for everything • obvious for Browser / Online games • Extreme: „There is no game entity class!“ • But: • There is always some code representation of the data • May not be feasable for small devices • Speed / memory footprint?
  • 22. 22 Reflection (1) • reflection • ability of a program to observe its internal structure at runtime • assembly code in memory can be read and interpreted • some scripting languages treat source code as strings • typically on a high level • figure out type of an object at runtime (introspection; polymorphism) • get the class name as a string • get method names as strings • figure out parameters and return types of methods • supported by Objective C, Java, C#, VB .Net, Managed C++
  • 23. 23 Reflection (2) • how does it work? • meta data generated by compiler • special interfaces to query type info from objects (= virtual functions) • lots of string lookups at runtime // trying to call: String FooNamespace.Foo.bar() Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo"); MethodInfo methodInfo = obj.GetType().GetMethod("bar"); // invoke the method, supplying parameter array with 0 size value = (String)methodInfo.Invoke(obj, new Object[0]); C#
  • 24. 24 Reflection (3) • Why doesn‘t C++ support this? • no single-rooted hierarchy • no common „Object“ base class for everything • void* is most “compatible” type • primitive types not really integrated into OO structure • Java and .NET have wrapper classes for them • .NET: “boxing” / “unboxing” mechanism • C++ supports early and late binding • i.e. supports non-virtual functions • ... and classed without a VTable • RTTI works for objects with VTable only • VTable is not generated just for RTTI
  • 25. 25 Reflection (4) • Reflection Libraries for C++ (just examples) • Seal Reflex • by European Organization for Nuclear Research (CERN) • uses external tool (based on ) GCCXML) to parse C++ code and generate reflection info • non-intrusive; generates external dictionary for code • up to date; supports latest gcc and VisualC++ • can add own meta-info to code (key-value-pairs) • http://seal-reflex.web.cern.ch Type t = Type::ByName("MyClass"); void * v = t.Allocate(); t.Destruct(v); Object o = t.Construct(); for (Member_Iterator mi = t.Member_Begin(); mi != t.Member_End(); ++mi) { switch ((*mi).MemberType()) { case DATAMEMBER : cout << "Datamember: " << (*mi).Name() << endl; case FUNCTIONMEMBER : cout << "Functionmember: " << (*mi).Name() << endl; } }
  • 26. 26 Reflection (5) • Reflection Libraries for C++ (just examples) • CppReflection • by Konstantin Knizhnik • reflection info supplied partly by programmer (through macros) • ... and partly taken from debug info generated by compiler • http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html class A { public: int i; protected: long larr[10]; A** ppa; public: RTTI_DESCRIBE_STRUCT((RTTI_FIELD(i, RTTI_FLD_PUBLIC), RTTI_ARRAY(larr, RTTI_FLD_PROTECTED), RTTI_PTR_TO_PTR(ppa, RTTI_FLD_PROTECTED))); };
  • 27. 27 Reflection (5) • Boost Reflection • by Jeremy Pack • not part of the boost libraries yet! • programmer must specify reflection info (through macros / templates) • http://boost-extension.blogspot.com • also possible: COM and CORBA • APIs that provide communication across language boundaries • also contain type description facilities
  • 28. 28 .NET Property System (1) class CTestClass { private int iSomeValue; public int SomeValue { get() { return iSomeValue; } set() { iSomeValue = value; } } } C# CTestClass pTestClass = new CTestClass(); pTestClass.SomeValue = 42; // implicitly calls set() System.Console.WriteLn(pTestClass.SomeValue); // implicitly calls get() C# • properties in .NET languages • ... look like member variables to the outside • ... but really are functions! •  syntactic alternative to get/set functions
  • 29. 29 .NET Property System (2) • just syntactic sugar? ref class CTestClass { private: int iSomeValue; public: property int SomeValue { int get() { return iSomeValue; } void set(int value) { iSomeValue = value; } } } Managed C++ CTestClass^ pTestClass = gcnew CTestClass; pTestClass->SomeValue = 42; System::Console::WriteLn(pTestClass->SomeValue); Managed C++
  • 30. 30 .NET Property System (3) • clean alternative to get/set methods • look like one data field from the outside • can still allow only get or only set • can be abstract, inherited, overwritten, work with polymorphism • interesting in connection with reflection • reflection can tell difference between a „property“ and normal methods • can add custom attributes to properties • through System.Attribute class • e.g. description text, author name... anything you want
  • 31. 31 PropertyGrid control displays and manipulates properties of any Object using reflection.
  • 32. 32 property names named property groups description text for each property custom editing controls for different property types validity criteria, e.g. minimum/maximum value, list of valid values lists of predefined values (but some of that is domain knowledge the editor has and not part or the property system
  • 33. 33 • windows forms editor clearly using domain knowledge to display special controls for some properties • can figure out the names of the enum entries using refelection, but not what „top“ or „fill“ means public enum class DockStyle { Bottom, Fill, Left, None, Right, Top } [LocalizableAttribute(true)] public: virtual property DockStyle Dock { DockStyle get (); void set (DockStyle value); }
  • 34. 34 Homebrew Properties! • accessing properties through functions  good idea! • clean: uses public API • object can react to changes • hides implementation from outside • Idea 1: • use member function pointers • i.e. existing get/set functions • Idea 2: • decouple per-instance and per-class data • type information needs to be kept only once per class!
  • 35. 35 CGenericProperty pUserObj : void* pDescription: CGenericPropertyDescription* GetTypeId() : type_info&; GetName() : string; GetDescriptionText() : string; GetSemantic() : string; GetDescription() : string; GetReadOnly() : string; CGenericPropertyDescription LoadFromString(void* pObject, const string& rsString) SaveToString(const void* pObject, string& rsString) m_sName : std::string; m_pType : const type_info*; m_sDesciptionText : std::string; m_bReadOnly : bool; m_sSemantic : std::string; per instance data: - client object - pointer to description = 8 bytes per class data size does not really matter property fetches most info from here
  • 36. 36 • CProperty does not add any data members! • can create array of CGenericProperty values and cast them as needed • not using polymorphism CGenericProperty pUserObj : void* pDescription: CGenericPropertyDescription* CProperty SetValue(T) GetValue() : T T : typename
  • 37. 37 CGenericPropertyDescription name, type, description, semantic... CGenericProperty GetValue(const void* pObject) : T SetValue(void* pObject, T xValue) CPropertyDescriptionScalar void (USERCLASS::*m_fpSetFunction)(T); T (USERCLASS::*m_fpGetFunction)() const; T m_xDefaultValue; T m_xMinValue; T m_xMaxValue; T : typename USERCLASS: typename T : typename CPropertyDescriptionEnum void (USERCLASS::*m_fpSetFunction)(int); int (USERCLASS::*m_fpGetFunction)() const; int m_iDefaultValue; std::vector<string> m_asPossibleValues; USERCLASS: typename works for: char, short, long, float, double Vec2, Vec3 contains enum values as strings
  • 38. 38 CPropertyDescriptionString<CCheckBox, string> CCheckBox::Prop_Text( "Text", "Text that appears next to CheckBox", false, "", &CCheckBox::SetText, &CCheckBox::GetText); CPropertyDescriptionEnum<CCheckBox> CCheckBox::Prop_State( "State", "Current state", false, "Unchecked", "Unchecked Checked Default", &CCheckBox::SetChecked, &CCheckBox::GetChecked); void CCheckBox::GetProperties(vector<CGenericProperty>& apxProperties) const { __super::GetProperties(apxProperties); apxProperties.push_back(CGenericProperty(&Prop_Text, (void*) this)); apxProperties.push_back(CGenericProperty(&Prop_State, (void*) this)); } class CCheckBox { enum CheckBoxState { CB_Unchecked, CB_Checked, CB_Default }; void SetChecked(int p_eChecked = CB_Checked); int GetChecked() const; void SetText(string sText); string GetText() const; void GetProperties(vector<CGenericProperty>& apxProperties) const; };
  • 39. 39 Homebrew Properties! • semantic • gives editor a hint how property is used • a string property could be... • ... a file name • ... a font name • ... or just a string • Validation / Range data • Different for each type • Scalar : min / max / default value • Enum: list of named values, default value • String: max length, allowed characters, default value
  • 40. 40 if you want the slides: david.salz@bitfield.de Questions / Comments? Thank you!