GObject

GObject
Developer(s)The GNOME Project
Initial release11 March 2002; 22 years ago (2002-03-11)
Written inC
Operating systemCross-platform
Available inMultilingual[which?]
TypeSoftware library
LicenseGNU LGPL
Websitedeveloper.gnome.org/gobject/stable/
As the GNU C Library serves as a wrapper for Linux kernel system calls, so do the libraries bundled in GLib (GObject, Glib, GModule, GThread and GIO) serve as further wrappers for their specific tasks.

The GLib Object System, or GObject, is a free software library providing a portable object system and transparent cross-language interoperability. GObject is designed for use both directly in C programs to provide object-oriented C-based APIs and through bindings to other languages to provide transparent cross-language interoperability, e.g. PyGObject.

History

Depending only on GLib and libc, GObject is a cornerstone of GNOME and is used throughout GTK, Pango, ATK, and most higher-level GNOME libraries like GStreamer and applications. Prior to GTK+ 2.0, code similar to GObject was part of the GTK codebase. (The name “GObject” was not yet in use — the common baseclass was called GtkObject.)

At the release of GTK+ 2.0, the object system was extracted into a separate library due to its general utility. In the process, most non-GUI-specific parts of the GtkObject class were moved up into GObject, the new common baseclass. Having existed as a separate library since March 11, 2002 (the release date of GTK+ 2.0), the GObject library is now used by many non-GUI programs such as command-line and server applications.

Relation to GLib

Though GObject has its own separate set of documentation[1] and is usually compiled into its own shared library file, the source code for GObject resides in the GLib source tree and is distributed along with GLib. For this reason, GObject uses the GLib version numbers and is typically packaged together with GLib (for example, Debian puts GObject in its libglib2.0 package family).

The type system

At the most basic level of the GObject framework lies a generic and dynamic type system called GType. The GType system holds a runtime description of all objects allowing glue code to facilitate multiple language bindings. The type system can handle any singly inherited class structure, in addition to non-classed types such as opaque pointers, strings, and variously sized integers and floating point numbers.

The type system knows how to copy, assign, and destroy values belonging to any of the registered types. This is trivial for types like integers, but many complex objects are reference-counted, while some are complex but not reference-counted. When the type system “copies” a reference-counted object, it will typically just increase its reference count, whereas when copying a complex, non-reference-counted object (such as a string), it will typically create an actual copy by allocating memory.

This basic functionality is used for implementing GValue, a type of generic container that can hold values of any type known by the type system. Such containers are particularly useful when interacting with dynamically typed language environments in which all native values reside in such type-tagged containers.

Fundamental types

Types that do not have any associated classes are called non-classed. These types, together with all types that correspond to some form of root class, are known as fundamental types: the types from which all other types are derived. These make up a relatively closed set, but although the average user is not expected to create their own fundamental types, the possibility does exist and has been exploited to create custom class hierarchies — i.e., class hierarchies not based on the GObject class.

As of GLib 2.9.2,[2] the non-classed built-in fundamental types are:

  • an empty type, corresponding to C's void (G_TYPE_NONE);
  • types corresponding to C's signed and unsigned char, int, long, and 64-bit integers (G_TYPE_CHAR, G_TYPE_UCHAR, G_TYPE_INT, G_TYPE_UINT, G_TYPE_LONG, G_TYPE_ULONG, G_TYPE_INT64, and G_TYPE_UINT64);
  • a Boolean type (G_TYPE_BOOLEAN);
  • an enumeration type and a “flags” type, both corresponding to C's enum type, but differing in that the latter is only used for bit fields (G_TYPE_ENUM and G_TYPE_FLAGS);
  • types for single- and double-precision IEEE floats, corresponding to C's float and double (G_TYPE_FLOAT and G_TYPE_DOUBLE);
  • a string type, corresponding to C's char * (G_TYPE_STRING);
  • an opaque pointer type, corresponding to C's void * (G_TYPE_POINTER).

The classed built-in fundamental types are:

  • a base class type for instances of GObject, the root of the standard class inheritance tree (G_TYPE_OBJECT)
  • a base interface type, analogous to the base class type but representing the root of the standard interface inheritance tree (G_TYPE_INTERFACE)
  • a type for boxed structures, which are used to wrap simple value objects or foreign objects in reference-counted “boxes” (G_TYPE_BOXED)
  • a type for “parameter specification objects,” which are used in GObject to describe metadata for object properties (G_TYPE_PARAM).

Types that can be instantiated automatically by the type system are called instantiable. An important characteristic of these types is that the first bytes of any instance always contain a pointer to the class structure (a form of virtual table) associated to the type of the instance. For this reason, any instantiable type must be classed. Contrapositively, any non-classed type (such as integer or string) must be non-instantiable. On the other hand, most classed types are instantiable, but some, such as interface types, are not.

Derived types

The types that are derived from the built-in GObject fundamental types fall roughly into four categories:

Enumerated types and “flags” types
In general, every enumerated type and every integer-based bitfield type (i.e., every enum type) that one wishes to use in some way that is related to the object system — for example, as the type of an object property — should be registered with the type system. Typically, the initialization code that takes care of registering these types is generated by an automated tool called glib-mkenums[3] and stored in a separate file.
Boxed types
Some data structures that are too simple to be made full-fledged class types (with all the overhead incurred) may still need to be registered with the type system. For example, we might have a class to which we want to add a background-color property, whose values should be instances of a structure that looks like struct color { int r, g, b; }. To avoid having to subclass GObject, we can create a boxed type to represent this structure, and provide functions for copying and freeing. GObject ships with a handful of boxed types wrapping simple GLib data types. Another use for boxed types is as a way to wrap foreign objects in a tagged container that the type system can identify and will know how to copy and free.
Opaque pointer types
Sometimes, for objects that need to be neither copied or reference-counted nor freed, even a boxed type would be overkill. While such objects can be used in GObject by simply treating them as opaque pointers (G_TYPE_POINTER), it is often a good idea to create a derived pointer type, documenting the fact that the pointers should reference a particular kind of object, even though nothing else is said about it.
Class and interface types
Most types in a GObject application will be classes — in the normal object-oriented sense of the word — derived directly or indirectly from the root class, GObject. There are also interfaces, which, unlike classic Java-style interfaces, can contain implemented methods. GObject interfaces can thus be described as mixins.

Messaging system

The GObject messaging system consists of two complementary parts: closures and signals.

Closures
A GObject closure is a generalized version of a callback. Support exists for closures written in C and C++, as well as arbitrary languages (when bindings are provided). This allows code written in (for example) Python and Java to be invoked via a GObject closure.
Signals
Signals are the primary mechanism by which closures are invoked. Objects register signal listeners with the type system, specifying a mapping between a given signal and a given closure. Upon emission of a registered signal, that signal's closure is invoked. In GTK, all native GUI events (such as mouse motion and keyboard actions) can generate GObject signals for listeners to potentially act upon.

Class implementation

Each GObject class is implemented by at least two structures: the class structure and the instance structure.

The class structure
The class structure corresponds to the vtable of a C++ class. It must begin with the class structure of the superclass. Following that, it will hold a set of function pointers — one for each virtual method of the class. Class-specific variables can be used to emulate class members.
The instance structure
The instance structure, which will exist in one copy per object instance, must begin with the instance structure of the superclass (this ensures that all instances begin with a pointer to the class structure, since all fundamental instantiable types share this property). After the data belonging to the superclass, the structure can hold any instance-specific variables, corresponding to C++ member variables.

Defining a class in the GObject framework is complex, requiring large amounts of boilerplate code, such as manual definitions of type casting macros and obscure type registration incantations. Also, since a C structure cannot have access modifiers like “public”, “protected”, or “private”, workarounds must be used to provide encapsulation. One approach is to include a pointer to the private data — conventionally called _priv — in the instance structure. The private structure can be declared in the public header file, but defined only in the implementation file, with the effect that the private data is opaque to users, but transparent to the implementor. If the private structure is registered with GType, it will be automatically allocated by the object system. Indeed, it is not even necessary to include the _priv pointer, if one is willing to use the incantation G_TYPE_INSTANCE_GET_PRIVATE every time the private data is needed.

To address some of these complexities, several higher-level languages exist that source-to-source compiles to GObject in C. The Vala programming language uses a C#-style syntax and is pre-processed into vanilla C code. The GObject Builder, or GOB2, offers a template syntax reminiscent of Java.

GObject Introspection

Usage

The combination of C and GObject is used in many successful free software projects, such as the GNOME desktop, the GTK toolkit and the GIMP image manipulation program.

Though many GObject applications are written entirely in C, the GObject system maps well into the native object systems of many other languages, like C++, Java, Ruby, Python, Common Lisp, and .NET/Mono. As a result, it is usually relatively painless to create language bindings for well-written libraries that use the GObject framework.

Writing GObject code in C in the first place, however, is relatively verbose. The library takes a good deal of time to learn, and programmers with experience in high-level object-oriented languages often find it somewhat tedious to work with GObject in C. For example, creating a subclass (even just a subclass of GObject) can require writing and/or copying large amounts of boilerplate code.[5] However, using Vala, a language that is designed primarily to work with GObject and which converts to C, is likely to make working with GObject or writing GObject based libraries nicer.

Although they are not really first-class objects (there are no actual metatypes in GType), metaobjects like classes and interfaces are created by GObject applications at runtime, and provide good support for introspection. The introspective capabilities are used by language bindings and user interface design applications like Glade to allow doing things like loading a shared library that provides a GObject class—usually some kind of widget, in the case of Glade—and then obtain a list of all properties of the class, complete with type information and documentation strings.

Comparisons to other object systems

Since GObject provides a mostly complete object system for C[citation needed], it can be seen as an alternative to C-derived languages such as C++ and Objective-C. (Though both also offer many other features beyond just their respective object systems.) An easily observed difference between C++ and GObject is that GObject (like Java) does not support multiple inheritance.[6]

GObject's use of GLib's g_malloc() memory allocation function will cause the program to exit unconditionally upon memory exhaustion, unlike the C library's malloc(), C++'s new, and other common memory allocators which allow a program to cope with or even fully recover from out-of-memory situations without simply crashing.[7] This tends to work against including GObject in software where resilience in the face of limited memory is important, or where very many or very large objects are commonly handled. The g_try_new() can be used when a memory allocation is more likely to fail (for a large object for example), but this cannot grant that the allocation will not fail elsewhere in the code.[8]

Another important difference is that while C++ and Objective-C are separate languages, GObject is strictly a library and as such does not introduce any new syntax or compiler intelligence. For example, when writing GObject-based C code, it is frequently necessary to perform explicit upcasting.[citation needed] Hence, “C with GObject”, also called "glib-flavored C", considered as a language separate from plain C, is a strict superset of plain C — like Objective C, but unlike C++.

On platforms where there is no standard ABI that works across all C++ compilers (which is not usually the case, since either the Itanium ABI or the Microsoft ABI are usually followed), a library compiled with one C++ compiler is not always able to call a library compiled with a different one.[citation needed] If such compatibility is required, the C++ methods must be exported as plain C functions, partly defeating the purpose of the C++ object system.[citation needed] The problem occurs in part because different C++ compilers use different kinds of name mangling to ensure the uniqueness of all exported symbols. (This is necessary because, for example, two different classes may have identically named member functions, one function name may be overloaded multiple times, or identically named functions may appear in different namespaces, but in object code these overlaps are not allowed.)[citation needed] In contrast, since C does not support any form of overloading or namespacing, authors of C libraries will typically use explicit prefixes to ensure the global uniqueness of their exported names. [citation needed] Hence, despite being object-oriented, a GObject-based library written in C will always use the same external symbol names regardless of which compiler is used.

Perhaps the most profound difference is GObject's emphasis on signals (called events in other languages).[citation needed] This emphasis derives from the fact that GObject was specifically designed to meet the needs of a GUI toolkit. Whilst there are signal libraries for most object-oriented languages out there, in the case of GObject it is built into the object system. Because of this, a typical GObject application will tend to use signals to a much larger extent than a non-GObject application would, making GObject components much more encapsulated and reusable than the ones using plain C++ or Java.[citation needed][according to whom?] If using glibmm/gtkmm, the official C++ wrappers to Glib/GTK respectively, the sibling project libsigc++ allows easy use of underlying GObject signals using standard C++. Of course, other implementations of signals are available on almost all platforms, although sometimes an extra library is needed, such as Boost.Signals2 for C++.

See also

References

  1. ^ "GObject Reference Manual".
  2. ^ "GObject Reference Manual - Stable".
  3. ^ "glib-mkenums, GObject Reference Manual".
  4. ^ "Introspection, Summary". Gnome Developer, Programming Guidelines - Specific How-Tos. Retrieved 9 August 2020.
  5. ^ "How to define and implement a new GObject". gnome.org. Retrieved 27 July 2013.
  6. ^ "c++ - Why Was the GObject System Created?". Stack Overflow. Retrieved 2019-11-16.
  7. ^ "Memory Allocation: GLib Reference Manual". developer.gnome.org. Retrieved 2019-11-16.
  8. ^ "Memory Allocation: GLib Reference Manual". developer.gnome.org. Retrieved 2019-11-17.

Read other articles:

Joaquín Fernández Cortina Retrato de Joaquín Fernández Cortina, obispo de Sigüenza, litografía de Luis Carlos Legrand Obispo de SigüenzaInformación religiosaOrdenación episcopal 1848.Información personalNacimiento Asturias, 1798.Fallecimiento Soria, 1854.Alma máter Universidad de Valladolid[editar datos en Wikidata] Joaquín Fernández Cortina (Pendueles, 15 de noviembre de 1798 - Montejo de Liceras, 31 de mayo de 1854) fue un eclesiástico español. Biografía Primeros a...

 

15. Eurovision Young Dancers Datum 16. Dezember 2017 Austragungsland Tschechien Tschechien Austragungsort Kongresszentrum, Prag Austragender Fernsehsender Moderation Libor Bouček & Angeé Klára Svobodová Teilnehmende Länder 8 Gewinner Polen Polen Zurückkehrende Teilnehmer Portugal Portugal Zurückgezogene Teilnehmer Albanien AlbanienNiederlande NiederlandeSlowakei Slowakei Abstimmungsregel Eine Fachjury wählt zwei Teilnehmer für das Finale aus. Der Sie...

 

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada April 2016. Mari kita potong rambut sesuai gaya hidup sosialisJosŏn-gŭl사회주의적생활양식에 맞게 머리단장을 하자 Hanja社會主義的生活樣式에 맞게 머리丹粧을 하자 Alih AksaraSahoe juuijeok saenghwal yangsige matge meori danjangeu...

Borstel Lambang kebesaranLetak Borstel di Segeberg NegaraJermanNegara bagianSchleswig-HolsteinKreisSegeberg Municipal assoc.Bad Bramstedt-LandPemerintahan • MayorEckhard KohnLuas • Total5,12 km2 (198 sq mi)Ketinggian13 m (43 ft)Populasi (2013-12-31)[1] • Total120 • Kepadatan0,23/km2 (0,61/sq mi)Zona waktuWET/WMPET (UTC+1/+2)Kode pos24616Kode area telepon04324Pelat kendaraanSESitus webwww.amt-bad-bramste...

 

Not to be confused with crater lakes, lakes of water that form in a volcanic crater or caldera. For places named Lava Lake, see Lava Lake. Molten lava contained in a volcanic crater Lava lake at Nyiragongo Volcano in a molten state. (Democratic Republic of the Congo) Lava lake at Erta Ale Volcano, Ethiopia. The lava lake of Halemaʻumaʻu at Kīlauea, Hawaiʻi, United States). Lava lake in Marum crater, Ambrym, Vanuatu. Satellite picture showing the lava lake of Mount Erebus, Antarctica....

 

此生者传记条目需要补充更多可供查證的来源。 (2021年7月7日)请协助補充可靠来源,无法查证的在世人物内容将被立即移除。 中天新聞台《中天晚間新聞》當家主播中天亞洲台新聞總監盧秀芳Lu Xiu Fang基本資料暱稱Lulu國籍 中華民國籍貫山東諸城出生 (1967-09-19) 1967年9月19日(56歲) 中華民國臺灣省基隆市安樂區最高學歷基隆女中、輔仁大學中文系婚姻狀況已婚配偶徐...

Hurricane season in the Atlantic Ocean 1964 Atlantic hurricane seasonSeason summary mapSeasonal boundariesFirst system formedJune 2, 1964Last system dissipatedNovember 10, 1964Strongest stormNameCleo • Maximum winds150 mph (240 km/h)(1-minute sustained) • Lowest pressure938 mbar (hPa; 27.7 inHg) Seasonal statisticsTotal depressions13Total storms13Hurricanes7Major hurricanes(Cat. 3+)5Total fatalities271Total damage~ $640.63 million (1964 USD)Related articles 1964 Pacifi...

 

2011 Indian filmSoloDirected byParasuramWritten byParasuramProduced byVamsikrishna SrinivasStarringNara Rohit Nisha Aggarwal Prakash RajSayaji ShindeJayasudhaAliCinematographyDasaradhi SivendraEdited byMarthand K. VenkateshMusic byMani SharmaProductioncompanyS.V.K CINEMARelease date 25 November 2011 (2011-11-25) CountryIndiaLanguageTelugu Solo is a 2011 Telugu language romantic family drama film written and directed by Parasuram. The film features Nara Rohit and Nisha Aggarwal ...

 

United States Army general This article is about the U.S. Army General. For the U.S. Appellate Court Judge, see Levin H. Campbell. Levin Hicks Campbell Jr.Major General Campbell at a press conference in December, 1942Born(1886-11-23)November 23, 1886Washington, D.C.DiedNovember 17, 1976(1976-11-17) (aged 89)Annapolis, MarylandBuriedUnited States Naval Academy Cemetery, AnnapolisAllegiance United States of AmericaService/branch United States ArmyYears of service1911 – ...

Modern collective term for Philippine writing systems Suyat (Baybayin: ᜐᜓᜌᜆ᜔, Hanunó'o: ᜰᜳᜬᜦ᜴, Buhid: ᝐᝓᝌ, Tagbanwa: ᝰᝳᝬ, Modern Kulitan: Jawi (Arabic): سُيَت‎) is the modern collective name of the indigenous scripts of various ethnolinguistic groups in the Philippines prior to Spanish colonization in the 16th century up to the independence era in the 21st century. The scripts are highly varied; nonetheless, the term was suggested and used by cultur...

 

For other uses, see 2012 (disambiguation). British TV series or programme Twenty TwelveGenreMockumentaryCreated byJohn MortonWritten byJohn MortonDirected byJohn MortonStarringHugh BonnevilleJessica HynesAmelia BullmoreOlivia ColmanVincent FranklinKarl TheobaldMorven ChristieNarrated byDavid TennantTheme music composerIrving BerlinOpening themeLet's Face the Music and Dance sung by Nat King ColeCountry of originUnited KingdomOriginal languageEnglishNo. of series2No. of episodes13Producti...

 

Mechanical knitting machine Stocking frame at Ruddington Framework Knitters' Museum A stocking frame was a mechanical knitting machine used in the textiles industry. It was invented by William Lee of Calverton near Nottingham in 1589. Its use, known traditionally as framework knitting, was the first major stage in the mechanisation of the textile industry, and played an important part in the early history of the Industrial Revolution. It was adapted to knit cotton and to do ribbing, and by 18...

American Paralympic athlete Rudy Garcia-TolsonPersonal informationNationalityAmericanBorn (1988-09-14) September 14, 1988 (age 35)Riverside, California, U.S. Medal record Men's swimming Representing  United States Paralympic Games 2004 Athens 200m Individual Medley SM7 2008 Beijing 200m Individual Medley SM7 2012 London 200m Individual Medley SM7 2016 Rio De Janeiro 200m Individual Medley SM7 2008 Beijing 100m Breaststroke SB7 IPC Swimming World Championships 2006 Durban 200m Indivi...

 

2016 single by Blonde and Craig DavidNothing Like ThisSingle by Blonde and Craig Davidfrom the album Following My Intuition Released18 March 2016Recorded2016Genre Deep house 2-step garage[1][2] Length3:03Label Parlophone FFRR Songwriter(s) Craig David Adam Englefield Jacob Manson Producer(s)BlondeBlonde singles chronology Feel Good (It's Alright) (2015) Nothing Like This (2016) Don't Need No Money (2016) Craig David singles chronology Who Am I(2016) Nothing Like This(2...

 

Indian actor This article uses bare URLs, which are uninformative and vulnerable to link rot. Please consider converting them to full citations to ensure the article remains verifiable and maintains a consistent citation style. Several templates and tools are available to assist in formatting, such as reFill (documentation) and Citation bot (documentation). (September 2022) (Learn how and when to remove this template message) PawanBorn (1971-10-17) 17 October 1971 (age 52)[1]Chen...

Francisco León de la Barra Presidente de los Estados Unidos MexicanosInterino 25 de mayo de 1911-6 de noviembre de 1911Gabinete Gabinete de Francisco León de la BarraVicepresidente Vacante[nota 1]​Predecesor Porfirio DíazSucesor Francisco I. Madero Secretario de Relaciones Exteriores 1 de abril de 1911-25 de mayo de 1911Presidente Porfirio DíazVicepresidente Ramón CorralPredecesor Enrique C. CreelSucesor Victoriano Salado Álvarez 21 de febrero de 1913-6 de julio de 1913Presidente ...

 

1994 TV film directed by Sam Pillsbury For other articles, see Knight Rider (disambiguation). Knight Rider 2010Promotional posterGenre Action Science fiction Based onKnight RiderWritten byJohn LeekleyDirected bySam PillsburyStarring Richard Joseph Paul Heidi Leick Michael Beach Don McManus Music byTim TrumanCountry of originUnited StatesOriginal languageEnglishProductionExecutive producers Rob Cohen John Leekley ProducerAlex BeatonCinematographyJames BartleEditorSkip SchoolnikRunning time86 m...

 

This article uses bare URLs, which are uninformative and vulnerable to link rot. Please consider converting them to full citations to ensure the article remains verifiable and maintains a consistent citation style. Several templates and tools are available to assist in formatting, such as reFill (documentation) and Citation bot (documentation). (September 2022) (Learn how and when to remove this template message) This article needs additional citations for verification. Please help improve th...

Untuk kegunaan lain, lihat Hizbullah (disambiguasi). Hizbullah回教青年挺身隊Kaikyō Seinen TeishintaiAktif8 Desember 1944–3 Juni 1947Negara Indonesia (pendudukan Jepang) (1944–1945) Indonesia (1945–1947)Aliansi MasyumiTipe unitInfanteriPeranPasukan cadangan bagi PETAPasukan paramiliterJumlah personelc. 25.000 personel (1945)MarkasCibarusah, Bekasi, Jawa BaratJulukanSabilillahWarna panji  Hijau  Merah  PutihUlang tahun8 DesemberPertempuranRevo...

 

Alpha and OmegaTheatrical release posterSutradaraAnthony BellBen GluckProduserKen KatsumotoSteve MooreRichard RichSkenarioChris DenkSteve MooreCeritaSteve MooreBen GluckPemeranJustin LongHayden PanettiereDennis HopperDanny GloverChris CarmackChristina RicciPenata musikChris P. BaconPenyuntingScott AndersonJoe CampanaPerusahaanproduksiCrest Animation ProductionsRelativity MediaDistributorLionsgate FilmsTanggal rilis17 September 2010Durasi90 menitNegaraAmerika SerikatKanadaBahasaInggrisAn...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!