gdextension_c_example.rst 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. .. _doc_gdextension_c_example:
  2. GDExtension C example
  3. =====================
  4. Introduction
  5. ------------
  6. This is a simple example on how to work with GDExtension directly with C code.
  7. Note that the API is not meant to be used directly, so this will definitely be
  8. quite verbose and require a lot of steps even for a small example. However, it
  9. serves as a reference for creating bindings for a different language. It is
  10. still possible to use the API directly if you prefer, which might be convenient
  11. when only binding a third-party library.
  12. In this example we will create a custom node that moves a sprite on the screen
  13. based on the user's parameters. While very simple, it serves to show how to do
  14. some of the things with GDExtension, like registering custom classes with
  15. methods, properties, and signals. It gives an insight on the GDExtension API.
  16. Setting up the project
  17. ----------------------
  18. There are a few prerequisites you'll need:
  19. - a Godot 4.2 (or later) executable,
  20. - a C compiler,
  21. - SCons as a build tool.
  22. Since this is using the API directly, there's no need to use the
  23. `godot-cpp repository <https://github.com/godotengine/godot-cpp>`__.
  24. File structure
  25. --------------
  26. To organize our files, we're gonna split into mainly two folders:
  27. .. code-block:: none
  28. gdextension_c_example/
  29. |
  30. +--demo/ # game example/demo to test the extension
  31. |
  32. +--src/ # source code of the extension we are building
  33. We also need a copy of the ``gdextension_interface.h`` header from the Godot
  34. source code, which can be obtained directly from the Godot executable by running
  35. the following command:
  36. .. code-block:: none
  37. godot --dump-gdextension-interface
  38. This creates the header in the current folder, so you can just copy it to the ``src``
  39. folder in the example project.
  40. Lastly, there's another source of information we need to refer to, which is the JSON
  41. file with the Godot API reference. This file won't be used by the code directly, we
  42. will only use it to extract some information manually.
  43. To get this JSON file, just call the Godot executable:
  44. .. code-block:: none
  45. godot --dump-extension-api
  46. The resulting ``extension_api.json`` file will be created in the current
  47. folder. You can copy this file to the example folder to have it handy.
  48. .. note::
  49. This extension is targeting Godot 4.2, but it should work on later versions as
  50. well. If you want to target a different minimal version, make sure to get the
  51. header and the JSON from the version Godot version you are targeting.
  52. Buildsystem
  53. -----------
  54. Using a buildsystem makes our life a lot easier when dealing with C code. For
  55. the sake of convenience, we'll use SCons since it's the same as what Godot
  56. itself uses.
  57. The following ``SConstruct`` file is a simple one that will build your extension
  58. to the current platform that you are using, be it Linux, macOS, or Windows. This
  59. will be a non-optimized build for debugging purposes. It also assumes a 64-bit
  60. build, which is relevant for some parts of the example code. Making other build
  61. types and cross-compilation is out of the scope of this tutorial. Save this file
  62. to the root folder.
  63. .. code-block:: python
  64. #!/bin/env python
  65. from SCons.Script import Environment
  66. from os import path
  67. import sys
  68. env = Environment()
  69. # Set the target path and name.
  70. target_path = "demo/bin/"
  71. target_name = "libgdexample"
  72. # Set the compiler and flags.
  73. env.Append(CPPPATH=["src"]) # Add the src folder to the include path.
  74. env.Append(CFLAGS=["-O0", "-g"]) # Make it a debug build.
  75. # Use Clang on macOS.
  76. if sys.platform == "darwin":
  77. env["CC"] = "clang"
  78. # Add all C files in "src" folder as sources.
  79. sources = env.Glob("src/*.c")
  80. # Create a shared library.
  81. library = env.SharedLibrary(
  82. target=path.join(target_path, target_name),
  83. source=sources,
  84. )
  85. # Set the library as the default target.
  86. env.Default(library)
  87. This will include all C files in the ``src`` folder, so we don't need to change
  88. this file when adding new source files.
  89. Initializing the extension
  90. --------------------------
  91. The first bit of code will be responsible for initializing the extension. This is
  92. what makes Godot aware of what our GDExtension provides, such as classes and
  93. plugins.
  94. Create the file ``init.h`` in the ``src`` folder, with the following contents:
  95. .. code-block:: c
  96. #pragma once
  97. #include "defs.h"
  98. #include "gdextension_interface.h"
  99. void initialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level);
  100. void deinitialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level);
  101. GDExtensionBool GDE_EXPORT gdexample_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization);
  102. The functions declared here have the signatures expected by the GDExtension API.
  103. Note the inclusion of the ``defs.h`` file. This is one of our helpers to
  104. simplify writing the extension code. For now it will only contain the definition
  105. of ``GDE_EXPORT``, a macro that makes the function public in the shared library
  106. so Godot can properly call it. This macro helps abstracting what each compiler
  107. expects.
  108. Create the ``defs.h`` file in the ``src`` folder with the following contents:
  109. .. code-block:: c
  110. #pragma once
  111. #include <stdbool.h>
  112. #include <stddef.h>
  113. #include <stdint.h>
  114. #if !defined(GDE_EXPORT)
  115. #if defined(_WIN32)
  116. #define GDE_EXPORT __declspec(dllexport)
  117. #elif defined(__GNUC__)
  118. #define GDE_EXPORT __attribute__((visibility("default")))
  119. #else
  120. #define GDE_EXPORT
  121. #endif
  122. #endif // ! GDE_EXPORT
  123. We also include some standard headers to make things easier. Now we only have to
  124. include ``defs.h`` and those will come as a bonus.
  125. Now, let's implement the functions we just declared. Create a file called
  126. ``init.c`` in the ``src`` folder and add this code:
  127. .. code-block:: c
  128. #include "init.h"
  129. void initialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level)
  130. {
  131. }
  132. void deinitialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level)
  133. {
  134. }
  135. GDExtensionBool GDE_EXPORT gdexample_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization)
  136. {
  137. r_initialization->initialize = initialize_gdexample_module;
  138. r_initialization->deinitialize = deinitialize_gdexample_module;
  139. r_initialization->userdata = NULL;
  140. r_initialization->minimum_initialization_level = GDEXTENSION_INITIALIZATION_SCENE;
  141. return true;
  142. }
  143. What this does is set up the initialization data that Godot expects. The
  144. functions to initialize and deinitialize are set so Godot will call then when
  145. needed. It also sets the initialization level which varies per extension. Since
  146. we plan to add a custom node, the ``SCENE`` level is enough.
  147. We will fill the ``initialize_gdexample_module()`` function later to register our custom class.
  148. A basic class
  149. -------------
  150. In order to make an actual node, first we'll create a C struct to hold data and
  151. functions that will act as methods. The plan is to make this a custom node that
  152. inherits from :ref:`Sprite2D <class_Sprite2D>`.
  153. Create a file called ``gdexample.h`` in the ``src`` folder with the following
  154. contents:
  155. .. code-block:: c
  156. #pragma once
  157. #include "gdextension_interface.h"
  158. #include "defs.h"
  159. // Struct to hold the node data.
  160. typedef struct
  161. {
  162. // Metadata.
  163. GDExtensionObjectPtr object; // Stores the underlying Godot object.
  164. } GDExample;
  165. // Constructor for the node.
  166. void gdexample_class_constructor(GDExample *self);
  167. // Destructor for the node.
  168. void gdexample_class_destructor(GDExample *self);
  169. // Bindings.
  170. void gdexample_class_bind_methods();
  171. Noteworthy here is the ``object`` field, which holds a pointer to
  172. the Godot object, and the ``gdexample_class_bind_methods()`` function, which will
  173. register the metadata of our custom class (properties, methods, and signals).
  174. The latter is not entirely necessary, as we can do it when registering the
  175. class, but it makes clearer to separate the concerns and let our class register
  176. its own metadata.
  177. The ``object`` field is necessary because our class will inherit a Godot class.
  178. Since we can't inherit it directly, as we are not interacting with the source
  179. code (and C doesn't even have classes), we instead tell Godot to create an
  180. object of a type it knows and attach our extension to it. We will need the
  181. reference to such objects when calling methods on the parent class, for
  182. instance.
  183. Let's create the source counterpart of this header. Create the file
  184. ``gdexample.c`` in the ``src`` folder and add the following code to it:
  185. .. code-block:: c
  186. #include "gdexample.h"
  187. void gdexample_class_constructor(GDExample *self)
  188. {
  189. }
  190. void gdexample_class_destructor(GDExample *self)
  191. {
  192. }
  193. void gdexample_class_bind_methods()
  194. {
  195. }
  196. As we don't have anything to do with those functions yet, they'll stay empty
  197. for a while.
  198. The next step is registering our class. However, in order to do so we need to
  199. create a :ref:`StringName <class_StringName>` and for that we have to get a
  200. function from the GDExtension API. Since we'll need this a few times and we'll
  201. also need other things, let's create a wrapper API to facilitate this kind of
  202. chore.
  203. A wrapper API
  204. -------------
  205. We'll start by creating an ``api.h`` file in the ``src`` folder:
  206. .. code-block:: c
  207. #pragma once
  208. /*
  209. This file works as a collection of helpers to call the GDExtension API
  210. in a less verbose way, as well as a cache for methods from the discovery API,
  211. just so we don't have to keep loading the same methods again.
  212. */
  213. #include "gdextension_interface.h"
  214. #include "defs.h"
  215. extern GDExtensionClassLibraryPtr class_library;
  216. // API methods.
  217. struct Constructors
  218. {
  219. GDExtensionInterfaceStringNameNewWithLatin1Chars string_name_new_with_latin1_chars;
  220. } constructors;
  221. struct Destructors
  222. {
  223. GDExtensionPtrDestructor string_name_destructor;
  224. } destructors;
  225. struct API
  226. {
  227. GDExtensionInterfaceClassdbRegisterExtensionClass2 classdb_register_extension_class2;
  228. } api;
  229. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address);
  230. This file will include many other helpers as we fill our extension with
  231. something useful. For now it only has a pointer to a function that creates a
  232. StringName from a C string (in Latin-1 encoding) and another to destruct a
  233. StringName, which we'll need to use to avoid leaking memory, as well as the
  234. function to register a class, which is our initial goal.
  235. We also keep a reference to the ``class_library`` here. This is something that
  236. Godot provides to us when initializing the extension and we'll need to use it
  237. when registering the things we create so Godot can tell which extension is
  238. making the call.
  239. There's also a function to load those function pointers from the GDExtension API.
  240. Let's work on the source counterpart of this header. Create the ``api.c`` file
  241. in the ``src`` folder, adding the following code:
  242. .. code-block:: c
  243. #include "api.h"
  244. GDExtensionClassLibraryPtr class_library = NULL;
  245. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  246. {
  247. // Get helper functions first.
  248. GDExtensionInterfaceVariantGetPtrDestructor variant_get_ptr_destructor = (GDExtensionInterfaceVariantGetPtrDestructor)p_get_proc_address("variant_get_ptr_destructor");
  249. // API.
  250. api.classdb_register_extension_class2 = p_get_proc_address("classdb_register_extension_class2");
  251. // Constructors.
  252. constructors.string_name_new_with_latin1_chars = p_get_proc_address("string_name_new_with_latin1_chars");
  253. // Destructors.
  254. destructors.string_name_destructor = variant_get_ptr_destructor(GDEXTENSION_VARIANT_TYPE_STRING_NAME);
  255. }
  256. The first important thing here is ``p_get_proc_address``. This a function from
  257. the GDExtension API that is passed during initialization. You can use this
  258. function to request specific functions from the API by their name. Here we are
  259. caching the results so we don't have to keep a reference for
  260. ``p_get_proc_address`` everywhere and use our wrapper instead.
  261. At the start we request the ``variant_get_ptr_destructor()`` function. This is not
  262. going to be used outside of this function, so we don't add to our wrapper and
  263. only cache it locally. The cast is necessary to silence compiler warnings.
  264. Then we get the function that creates a StringName from a C string, exactly what
  265. we mentioned before as a needed function. We store that in our ``constructors``
  266. struct.
  267. Next, we use the ``variant_get_ptr_destructor()`` function we just got to query
  268. for the destructor for StringName, using the enum value from
  269. ``gdextension_interface.h`` API as a parameter. We could get destructors for
  270. other types in a similar manner, but we'll limit ourselves to what is needed for
  271. the example.
  272. Lastly, we get the ``classdb_register_extension_class2()`` function, which we'll
  273. need in order to register our custom class.
  274. .. note::
  275. You may wonder why the ``2`` is there in the function name. This means it's the
  276. second version of this function. The old version is kept to ensure backwards
  277. compatibility with older extensions, but since we have the second version
  278. available, it's best to use the new one, because we don't intend to support older
  279. Godot versions in this example.
  280. The ``gdextension_interface.h`` header documents in which Godot version each
  281. function was introduced.
  282. We also define the ``class_library`` variable here, which will be set during
  283. initialization.
  284. Speaking of initialization, now we have to change the ``init.c`` file in
  285. order to fill the things we just added:
  286. .. code-block:: c
  287. GDExtensionBool GDE_EXPORT gdexample_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization)
  288. {
  289. class_library = p_library;
  290. load_api(p_get_proc_address);
  291. ...
  292. Here we set the ``class_library`` as needed and call our new ``load_api()``
  293. function. Don't forget to also include the new headers at the top of this file:
  294. .. code-block:: c
  295. #include "init.h"
  296. #include "api.h"
  297. #include "gdexample.h"
  298. ...
  299. Since we are here, we can register our new custom class. Let's fill the
  300. ``initialize_gdexample_module()`` function:
  301. .. code-block:: c
  302. void initialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level)
  303. {
  304. if (p_level != GDEXTENSION_INITIALIZATION_SCENE)
  305. {
  306. return;
  307. }
  308. // Register class.
  309. StringName class_name;
  310. constructors.string_name_new_with_latin1_chars(&class_name, "GDExample", false);
  311. StringName parent_class_name;
  312. constructors.string_name_new_with_latin1_chars(&parent_class_name, "Sprite2D", false);
  313. GDExtensionClassCreationInfo2 class_info = {
  314. .is_virtual = false,
  315. .is_abstract = false,
  316. .is_exposed = true,
  317. .set_func = NULL,
  318. .get_func = NULL,
  319. .get_property_list_func = NULL,
  320. .free_property_list_func = NULL,
  321. .property_can_revert_func = NULL,
  322. .property_get_revert_func = NULL,
  323. .validate_property_func = NULL,
  324. .notification_func = NULL,
  325. .to_string_func = NULL,
  326. .reference_func = NULL,
  327. .unreference_func = NULL,
  328. .create_instance_func = gdexample_class_create_instance,
  329. .free_instance_func = gdexample_class_free_instance,
  330. .recreate_instance_func = NULL,
  331. .get_virtual_func = NULL,
  332. .get_virtual_call_data_func = NULL,
  333. .call_virtual_with_data_func = NULL,
  334. .get_rid_func = NULL,
  335. .class_userdata = NULL,
  336. };
  337. api.classdb_register_extension_class2(class_library, &class_name, &parent_class_name, &class_info);
  338. // Bind methods.
  339. gdexample_class_bind_methods();
  340. // Destruct things.
  341. destructors.string_name_destructor(&class_name);
  342. destructors.string_name_destructor(&parent_class_name);
  343. }
  344. The struct with the class information is the biggest thing here. None of its
  345. fields are required with the exception of ``create_instance_func`` and
  346. ``free_instance_func``. We haven't made those functions yet, so we'll have
  347. to work on them soon. Note that we skip the initialization if it isn't at the
  348. ``SCENE`` level. This function may be called multiple times, once for each
  349. level, but we only want to register our class once.
  350. The other undefined thing here is ``StringName``. This will be an opaque struct
  351. meant to hold the data of a Godot StringName in our extension. We'll define it
  352. in the appropriately named ``defs.h`` file:
  353. .. code-block:: c
  354. ...
  355. // The sizes can be obtained from the extension_api.json file.
  356. #ifdef BUILD_32
  357. #define STRING_NAME_SIZE 4
  358. #else
  359. #define STRING_NAME_SIZE 8
  360. #endif
  361. // Types.
  362. typedef struct
  363. {
  364. uint8_t data[STRING_NAME_SIZE];
  365. } StringName;
  366. #endif // DEFS_H
  367. As mentioned in the comment, the sizes can be found in the
  368. ``extension_api.json`` file that we generated earlier, under the
  369. ``builtin_class_sizes`` property. The ``BUILD_32`` is never defined, as we
  370. assume we are working with a 64-bits build of Godot here, but if you need it you
  371. can add ``env.Append(CPPDEFINES=["BUILD_32"])`` to your ``SConstruct`` file.
  372. The ``// Types.`` comment foreshadows that we'll be adding more types to this
  373. file. Let's leave that for later.
  374. The ``StringName`` struct here is just to hold Godot data, so we don't really
  375. care what is inside of it. Though, in this case, it is just a pointer to the
  376. data in the heap. We'll use this struct when we need to allocate data for a
  377. StringName ourselves, like we are doing when registering our class.
  378. Back to registering, we need to work on our create and free functions. Let's
  379. include them in ``gdexample.h`` since they're specific to the custom class:
  380. .. code-block:: c
  381. ...
  382. // Bindings.
  383. void gdexample_class_bind_methods();
  384. GDExtensionObjectPtr gdexample_class_create_instance(void *p_class_userdata);
  385. void gdexample_class_free_instance(void *p_class_userdata, GDExtensionClassInstancePtr p_instance);
  386. ...
  387. Before we can implement those function, we'll need a few more things in our API.
  388. We need a way to allocate and free memory. While we could do this with good ol'
  389. ``malloc()``, we can instead make use of Godot's memory management functions.
  390. We'll also need a way to create a Godot object and set it with our custom
  391. instance.
  392. So let's change the ``api.h`` to include these new functions:
  393. .. code-block:: c
  394. ...
  395. struct API
  396. {
  397. GDExtensionInterfaceClassdbRegisterExtensionClass2 classdb_register_extension_class2;
  398. GDExtensionInterfaceClassdbConstructObject classdb_construct_object;
  399. GDExtensionInterfaceObjectSetInstance object_set_instance;
  400. GDExtensionInterfaceObjectSetInstanceBinding object_set_instance_binding;
  401. GDExtensionInterfaceMemAlloc mem_alloc;
  402. GDExtensionInterfaceMemFree mem_free;
  403. } api;
  404. Then we change the ``load_api()`` function in ``api.c`` to grab these new functions:
  405. .. code-block:: c
  406. ...
  407. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  408. {
  409. ...
  410. // API.
  411. api.classdb_register_extension_class2 = p_get_proc_address("classdb_register_extension_class2");
  412. api.classdb_construct_object = (GDExtensionInterfaceClassdbConstructObject)p_get_proc_address("classdb_construct_object");
  413. api.object_set_instance = p_get_proc_address("object_set_instance");
  414. api.object_set_instance_binding = p_get_proc_address("object_set_instance_binding");
  415. api.mem_alloc = (GDExtensionInterfaceMemAlloc)p_get_proc_address("mem_alloc");
  416. api.mem_free = (GDExtensionInterfaceMemFree)p_get_proc_address("mem_free");
  417. }
  418. Now we can go back to ``gdexample.c`` and define the new functions, without forgetting to
  419. include the ``api.h`` header:
  420. .. code-block:: c
  421. #include "gdexample.h"
  422. #include "api.h"
  423. ...
  424. const GDExtensionInstanceBindingCallbacks gdexample_class_binding_callbacks = {
  425. .create_callback = NULL,
  426. .free_callback = NULL,
  427. .reference_callback = NULL,
  428. };
  429. GDExtensionObjectPtr gdexample_class_create_instance(void *p_class_userdata)
  430. {
  431. // Create native Godot object;
  432. StringName class_name;
  433. constructors.string_name_new_with_latin1_chars(&class_name, "Sprite2D", false);
  434. GDExtensionObjectPtr object = api.classdb_construct_object(&class_name);
  435. destructors.string_name_destructor(&class_name);
  436. // Create extension object.
  437. GDExample *self = (GDExample *)api.mem_alloc(sizeof(GDExample));
  438. gdexample_class_constructor(self);
  439. self->object = object;
  440. // Set the extension instance in the native Godot object.
  441. constructors.string_name_new_with_latin1_chars(&class_name, "GDExample", false);
  442. api.object_set_instance(object, &class_name, self);
  443. api.object_set_instance_binding(object, class_library, self, &gdexample_class_binding_callbacks);
  444. destructors.string_name_destructor(&class_name);
  445. return object;
  446. }
  447. void gdexample_class_free_instance(void *p_class_userdata, GDExtensionClassInstancePtr p_instance)
  448. {
  449. if (p_instance == NULL)
  450. {
  451. return;
  452. }
  453. GDExample *self = (GDExample *)p_instance;
  454. gdexample_class_destructor(self);
  455. api.mem_free(self);
  456. }
  457. When instantiating an object, first we create a new Sprite2D object, since
  458. that's the parent of our class. Then we allocate memory for our custom struct
  459. and call its constructor. We save the pointer to the Godot object in the struct
  460. as well like we mentioned earlier.
  461. Then we set our custom struct as the instance data. This will make Godot know
  462. that the object is an instance of our custom class and properly call our custom
  463. methods for instance, as well as passing this data back.
  464. Note that we return the Godot object we created, not our custom struct.
  465. For the ``gdextension_free_instance()`` function, we only call the destructor and free the memory we
  466. allocated for the custom data. It is not necessary to destruct the Godot object
  467. since that will be taken care of by the engine itself.
  468. A demo project
  469. --------------
  470. Now that we can create and free our custom object, we should be able to try it
  471. out in an actual project. For this, you need to open Godot and create a new
  472. project on the ``demo`` folder. The project manager may warn you the folder
  473. isn't empty if you have compiled the extension before, you can safely ignore
  474. this warning this time.
  475. If you didn't compile the extension yet, it is the time to do it now. To do
  476. that, open a terminal or command prompt, navigate to the root folder of the
  477. extension and run ``scons``. It should compile quickly since the extension is
  478. very simple.
  479. Then, create a file called ``gdexample.gdextension`` inside the ``demo`` folder.
  480. This is a Godot resource that describes the extension, allowing the engine to
  481. properly load it. Put the following content in this file:
  482. .. code-block::
  483. [configuration]
  484. entry_symbol = "gdexample_library_init"
  485. compatibility_minimum = "4.2"
  486. [libraries]
  487. macos.debug = "res://bin/libgdexample.dylib"
  488. linux.debug = "res://bin/libgdexample.so"
  489. windows.debug = "res://bin/libgdexample.dll"
  490. As you can see, ``gdexample_library_init()`` is the same name of the function we
  491. defined in our ``init.c`` file. It is important that the names match because it
  492. is how Godot calls the entry point of the extension.
  493. We also set the compatibility minimum to 4.2, since we are targeting this
  494. version. It should still work on later versions. If you are using a later Godot
  495. version and rely on the new features, you need to increase this value to a
  496. version number that has everything you use.
  497. See :ref:`doc_what_is_gdextension_version_compatibility` for more information.
  498. In the ``[libraries]`` section we set up the paths to the shared library on
  499. different platforms. Here there's only the debug versions since that's what we
  500. are working on for the example. Using :ref:`feature tags <doc_feature_tags>` you
  501. can fine tune this to also provide release versions, add more target operating systems, as
  502. well as providing 32-bit and 64-bit binaries.
  503. You can also add library dependencies and custom icons for your classes in this
  504. file, but this is out of the scope for this tutorial.
  505. After saving the file, go back to the editor. Godot should automatically load
  506. the extension. Nothing will be seen because our extension only registers a new
  507. class. To use this class add a ``Node2D`` as a root of the scene. Move it to
  508. the middle of viewport for better visibility. Then add a new child node to the
  509. root and in the **Create New Node** dialog search for "GDExample", the name of
  510. our class, as it should be listed there. If it isn't, it means that Godot didn't
  511. load the extension properly, so try restarting the editor and retrace the steps
  512. to see if anything went missing.
  513. Our custom class is derived from ``Sprite2D``, so it has a **Texture** property
  514. in the Inspector. Set this to the ``icon.svg`` file that Godot handily created
  515. for us when making the project. Save this scene as ``main.tscn`` and run it. You
  516. may want to set it as the main scene for convenience.
  517. .. image:: img/gdextension_c_running.webp
  518. Voilà! We have a custom node running in Godot. However, it does not do anything
  519. and has nothing different than a regular ``Sprite2D`` node. We will fix that next by
  520. adding custom methods and properties.
  521. Custom methods
  522. --------------
  523. A common thing in extensions is creating methods for the custom classes and
  524. exposing those to the Godot API. We are going to create a couple of getters and
  525. setters which are need for binding the properties afterwards.
  526. First, let's add the new fields in our struct to hold the values for
  527. ``amplitude`` and ``speed``, which we will use later on when creating the
  528. behavior for the node. Add them to the ``gdexample.h`` file, changing the
  529. ``GDExample`` struct:
  530. .. code-block:: c
  531. ...
  532. typedef struct
  533. {
  534. // Public properties.
  535. double amplitude;
  536. double speed;
  537. // Metadata.
  538. GDExtensionObjectPtr object; // Stores the underlying Godot object.
  539. } GDExample;
  540. ...
  541. In the same file, add the declaration for the getters and setters, right after
  542. the destructor.
  543. .. code-block:: c
  544. ...
  545. // Destructor for the node.
  546. void gdexample_class_destructor(GDExample *self);
  547. // Properties.
  548. void gdexample_class_set_amplitude(GDExample *self, double amplitude);
  549. double gdexample_class_get_amplitude(const GDExample *self);
  550. void gdexample_class_set_speed(GDExample *self, double speed);
  551. double gdexample_class_get_speed(const GDExample *self);
  552. ...
  553. In the ``gdexample.c`` file, we will initialize these values in the constructor
  554. and add the implementations for those new functions, which are quite trivial:
  555. .. code-block:: c
  556. void gdexample_class_constructor(GDExample *self)
  557. {
  558. self->amplitude = 10.0;
  559. self->speed = 1.0;
  560. }
  561. void gdexample_class_set_amplitude(GDExample *self, double amplitude)
  562. {
  563. self->amplitude = amplitude;
  564. }
  565. double gdexample_class_get_amplitude(const GDExample *self)
  566. {
  567. return self->amplitude;
  568. }
  569. void gdexample_class_set_speed(GDExample *self, double speed)
  570. {
  571. self->speed = speed;
  572. }
  573. double gdexample_class_get_speed(const GDExample *self)
  574. {
  575. return self->speed;
  576. }
  577. To make those simple functions work when called by Godot, we will need some
  578. wrappers to help us properly convert the data to and from the engine.
  579. First, we will create wrappers for ``ptrcall``. This is what Godot uses when the
  580. types of the values are known to be exact, which avoids using Variant. We're
  581. gonna need two of those: one for the functions that take no arguments and
  582. return a ``double`` (for the getters) and another for the functions that take a
  583. single ``double`` argument and return nothing (for the setters).
  584. Add the declarations to the ``api.h`` file:
  585. .. code-block:: c
  586. void ptrcall_0_args_ret_float(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr r_ret);
  587. void ptrcall_1_float_arg_no_ret(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr r_ret);
  588. Those two functions follow the ``GDExtensionClassMethodPtrCall`` type, as
  589. defined in the ``gdextension_interface.h``. We use ``float`` as a name here
  590. because in Godot the ``float`` type has double precision, so we keep this
  591. convention.
  592. Then we implement those functions in the ``api.c`` file:
  593. .. code-block:: c
  594. void ptrcall_0_args_ret_float(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr r_ret)
  595. {
  596. // Call the function.
  597. double (*function)(void *) = method_userdata;
  598. *((double *)r_ret) = function(p_instance);
  599. }
  600. void ptrcall_1_float_arg_no_ret(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr r_ret)
  601. {
  602. // Call the function.
  603. void (*function)(void *, double) = method_userdata;
  604. function(p_instance, *((double *)p_args[0]));
  605. }
  606. The ``method_userdata`` argument is a custom value that we give to Godot, in
  607. this case we will set as the function pointer for the one we want to call. So
  608. first we convert it to the function type, then we just call it by passing the
  609. arguments when needed, or setting the return value.
  610. The ``p_instance`` argument contains the custom instance of our class, which we
  611. gave with ``object_set_instance()`` when creating the object.
  612. ``p_args`` is an array of arguments. Note this contains **pointers** to the
  613. values. That's why we dereference it when passing to our functions. The number
  614. of arguments will be declared when binding the function (which we will do soon)
  615. and it will always include default ones if those exist.
  616. Finally, the ``r_ret`` is a pointer to the variable where the return value needs to
  617. be set. Like the arguments, it will be the correct type as declared. For the
  618. function that does not return, we have to avoid setting it.
  619. Note how the type and argument counts are exact, so if we needed different
  620. types, for example, we would have to create more wrappers. This could be
  621. automated using some code generation, but this is out of the scope for this
  622. tutorial.
  623. While the ``ptrcall`` functions are used when types are exact, sometimes Godot cannot know
  624. if that's the case (when the call comes from a dynamically typed language, such
  625. as GDScript). In those situations it uses regular ``call`` functions, so we need to
  626. provide those as well when binding.
  627. Let's create two new wrappers in the ``api.h`` file:
  628. .. code-block:: c
  629. void call_0_args_ret_float(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstVariantPtr *p_args, GDExtensionInt p_argument_count, GDExtensionVariantPtr r_return, GDExtensionCallError *r_error);
  630. void call_1_float_arg_no_ret(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstVariantPtr *p_args, GDExtensionInt p_argument_count, GDExtensionVariantPtr r_return, GDExtensionCallError *r_error);
  631. These follow the ``GDExtensionClassMethodCall`` type, which is a bit different.
  632. First, you receive pointers to Variants instead of exact types. There's also the
  633. amount of arguments and an error struct that you can set if something goes
  634. wrong.
  635. In order to check the type and also extract interact with Variant, we will need
  636. a few more functions from the GDExtension API. So let's expand our wrapper
  637. structs:
  638. .. code-block:: c
  639. struct Constructors {
  640. ...
  641. GDExtensionVariantFromTypeConstructorFunc variant_from_float_constructor;
  642. GDExtensionTypeFromVariantConstructorFunc float_from_variant_constructor;
  643. } constructors;
  644. struct API
  645. {
  646. ...
  647. GDExtensionInterfaceGetVariantFromTypeConstructor get_variant_from_type_constructor;
  648. GDExtensionInterfaceGetVariantToTypeConstructor get_variant_to_type_constructor;
  649. GDExtensionInterfaceVariantGetType variant_get_type;
  650. } api;
  651. The names say all about what those do. We have a couple of constructors to
  652. create and extract a floating point value to and from a Variant. We also have a
  653. couple of helpers to actually get those constructors, as well as a function to
  654. find out the type of a Variant.
  655. Let's get those from the API, like we did before, by changing the ``load_api()``
  656. function in the ``api.c`` file:
  657. .. code-block:: c
  658. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  659. {
  660. ...
  661. // API.
  662. ...
  663. api.get_variant_from_type_constructor = (GDExtensionInterfaceGetVariantFromTypeConstructor)p_get_proc_address("get_variant_from_type_constructor");
  664. api.get_variant_to_type_constructor = (GDExtensionInterfaceGetVariantToTypeConstructor)p_get_proc_address("get_variant_to_type_constructor");
  665. api.variant_get_type = (GDExtensionInterfaceVariantGetType)p_get_proc_address("variant_get_type");
  666. ...
  667. // Constructors.
  668. ...
  669. constructors.variant_from_float_constructor = api.get_variant_from_type_constructor(GDEXTENSION_VARIANT_TYPE_FLOAT);
  670. constructors.float_from_variant_constructor = api.get_variant_to_type_constructor(GDEXTENSION_VARIANT_TYPE_FLOAT);
  671. ...
  672. }
  673. Now that we have these set, we can implement our call wrappers in the same file:
  674. .. code-block:: c
  675. void call_0_args_ret_float(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstVariantPtr *p_args, GDExtensionInt p_argument_count, GDExtensionVariantPtr r_return, GDExtensionCallError *r_error)
  676. {
  677. // Check argument count.
  678. if (p_argument_count != 0)
  679. {
  680. r_error->error = GDEXTENSION_CALL_ERROR_TOO_MANY_ARGUMENTS;
  681. r_error->expected = 0;
  682. return;
  683. }
  684. // Call the function.
  685. double (*function)(void *) = method_userdata;
  686. double result = function(p_instance);
  687. // Set resulting Variant.
  688. constructors.variant_from_float_constructor(r_return, &result);
  689. }
  690. void call_1_float_arg_no_ret(void *method_userdata, GDExtensionClassInstancePtr p_instance, const GDExtensionConstVariantPtr *p_args, GDExtensionInt p_argument_count, GDExtensionVariantPtr r_return, GDExtensionCallError *r_error)
  691. {
  692. // Check argument count.
  693. if (p_argument_count < 1)
  694. {
  695. r_error->error = GDEXTENSION_CALL_ERROR_TOO_FEW_ARGUMENTS;
  696. r_error->expected = 1;
  697. return;
  698. }
  699. else if (p_argument_count > 1)
  700. {
  701. r_error->error = GDEXTENSION_CALL_ERROR_TOO_MANY_ARGUMENTS;
  702. r_error->expected = 1;
  703. return;
  704. }
  705. // Check the argument type.
  706. GDExtensionVariantType type = api.variant_get_type(p_args[0]);
  707. if (type != GDEXTENSION_VARIANT_TYPE_FLOAT)
  708. {
  709. r_error->error = GDEXTENSION_CALL_ERROR_INVALID_ARGUMENT;
  710. r_error->expected = GDEXTENSION_VARIANT_TYPE_FLOAT;
  711. r_error->argument = 0;
  712. return;
  713. }
  714. // Extract the argument.
  715. double arg1;
  716. constructors.float_from_variant_constructor(&arg1, (GDExtensionVariantPtr)p_args[0]);
  717. // Call the function.
  718. void (*function)(void *, double) = method_userdata;
  719. function(p_instance, arg1);
  720. }
  721. These functions are a bit longer but easy to follow. First they check if the
  722. argument count is as expected and if not they set the error struct and
  723. return. For the one that has one parameter, it also checks if the argument type
  724. is correct. This is important because mismatched types when extracting from
  725. Variant can cause crashes.
  726. Then it proceeds to extract the argument using the constructor we setup before.
  727. The one with no arguments instead sets the return value after calling the
  728. function. Note how they use a pointer to a ``double`` variable, since this is
  729. what those constructors expect.
  730. Before we can actually bind our methods, we need a way to create
  731. ``GDExtensionPropertyInfo`` instances. While we could do them inside the binding
  732. functions that we'll implement afterwards, it's easier to have a helper for it
  733. since we'll need it multiple times, including for when we bind properties.
  734. Let's create these two functions in the ``api.h`` file:
  735. .. code-block:: c
  736. // Create a PropertyInfo struct.
  737. GDExtensionPropertyInfo make_property(
  738. GDExtensionVariantType type,
  739. const char *name);
  740. GDExtensionPropertyInfo make_property_full(
  741. GDExtensionVariantType type,
  742. const char *name,
  743. uint32_t hint,
  744. const char *hint_string,
  745. const char *class_name,
  746. uint32_t usage_flags);
  747. void destruct_property(GDExtensionPropertyInfo *info);
  748. The first one is a simplified version of the second since we usually don't need
  749. all the arguments for the property and are okay with the defaults. Then we also
  750. have a function to destruct the PropertyInfo since we need to create Strings and
  751. StringNames that need to be properly disposed of.
  752. Speaking of which, we also need a way to create and destruct Strings, so we'll
  753. make an addition to existing structs in this same file. We'll also get a new API
  754. function for actually binding our custom method.
  755. .. code-block:: c
  756. struct Constructors
  757. {
  758. ...
  759. GDExtensionInterfaceStringNewWithUtf8Chars string_new_with_utf8_chars;
  760. } constructors;
  761. struct Destructors
  762. {
  763. ...
  764. GDExtensionPtrDestructor string_destructor;
  765. } destructors;
  766. struct API
  767. {
  768. ...
  769. GDExtensionInterfaceClassdbRegisterExtensionClassMethod classdb_register_extension_class_method;
  770. } api;
  771. Before implementing those, let's do a quick stop in the ``defs.h`` file and
  772. include the size of the ``String`` type and a couple of enums:
  773. .. code-block:: c
  774. // The sizes can be obtained from the extension_api.json file.
  775. #ifdef BUILD_32
  776. #define STRING_SIZE 4
  777. #define STRING_NAME_SIZE 4
  778. #else
  779. #define STRING_SIZE 8
  780. #define STRING_NAME_SIZE 8
  781. #endif
  782. ...
  783. typedef struct
  784. {
  785. uint8_t data[STRING_SIZE];
  786. } String;
  787. // Enums.
  788. typedef enum
  789. {
  790. PROPERTY_HINT_NONE = 0,
  791. } PropertyHint;
  792. typedef enum
  793. {
  794. PROPERTY_USAGE_NONE = 0,
  795. PROPERTY_USAGE_STORAGE = 2,
  796. PROPERTY_USAGE_EDITOR = 4,
  797. PROPERTY_USAGE_DEFAULT = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR,
  798. } PropertyUsageFlags;
  799. While it's the same size as ``StringName``, it is more clear to use a different
  800. name for it.
  801. The enums here are just helpers to give names to the numbers they represent. The
  802. information about them is present in the ``extension_api.json`` file. Here we
  803. just set up the ones we need for the tutorial, to keep it more concise.
  804. Going now to the ``api.c``, we need to load the pointers to the new functions we
  805. added to the API.
  806. .. code-block:: c
  807. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  808. {
  809. ...
  810. // API
  811. ...
  812. api.classdb_register_extension_class_method = p_get_proc_address("classdb_register_extension_class_method");
  813. // Constructors.
  814. ...
  815. constructors.string_new_with_utf8_chars = p_get_proc_address("string_new_with_utf8_chars");
  816. // Destructors.
  817. ...
  818. destructors.string_destructor = variant_get_ptr_destructor(GDEXTENSION_VARIANT_TYPE_STRING);
  819. }
  820. Then we can also implement the functions to create the ``PropertyInfo`` struct.
  821. .. code-block:: c
  822. GDExtensionPropertyInfo make_property(
  823. GDExtensionVariantType type,
  824. const char *name)
  825. {
  826. return make_property_full(type, name, PROPERTY_HINT_NONE, "", "", PROPERTY_USAGE_DEFAULT);
  827. }
  828. GDExtensionPropertyInfo make_property_full(
  829. GDExtensionVariantType type,
  830. const char *name,
  831. uint32_t hint,
  832. const char *hint_string,
  833. const char *class_name,
  834. uint32_t usage_flags)
  835. {
  836. StringName *prop_name = api.mem_alloc(sizeof(StringName));
  837. constructors.string_name_new_with_latin1_chars(prop_name, name, false);
  838. String *prop_hint_string = api.mem_alloc(sizeof(String));
  839. constructors.string_new_with_utf8_chars(prop_hint_string, hint_string);
  840. StringName *prop_class_name = api.mem_alloc(sizeof(StringName));
  841. constructors.string_name_new_with_latin1_chars(prop_class_name, class_name, false);
  842. GDExtensionPropertyInfo info = {
  843. .name = prop_name,
  844. .type = type,
  845. .hint = hint,
  846. .hint_string = prop_hint_string,
  847. .class_name = prop_class_name,
  848. .usage = usage_flags,
  849. };
  850. return info;
  851. }
  852. void destruct_property(GDExtensionPropertyInfo *info)
  853. {
  854. destructors.string_name_destructor(info->name);
  855. destructors.string_destructor(info->hint_string);
  856. destructors.string_name_destructor(info->class_name);
  857. api.mem_free(info->name);
  858. api.mem_free(info->hint_string);
  859. api.mem_free(info->class_name);
  860. }
  861. The simple version of ``make_property()`` just calls the more complete one with a
  862. some default arguments. What those values mean exactly is out of the scope of
  863. this tutorial, check the page about the :ref:`Object class <doc_object_class>`
  864. for more details about binding methods and properties.
  865. The complete version is more involved. First, it creates ``String``'s and
  866. ``StringName``'s for the needed fields, by allocating memory and calling their
  867. constructors. Then it creates a ``GDExtensionPropertyInfo`` struct and sets all
  868. the fields with the arguments provided. Finally it returns this created struct.
  869. The ``destruct_property()`` function is straightforward, it simply calls the
  870. destructors for the created objects and frees their allocated memory.
  871. Let's go back again to the header ``api.h`` to create the functions that will
  872. actually bind the methods:
  873. .. code-block:: c
  874. // Version for 0 arguments, with return.
  875. void bind_method_0_r(
  876. const char *class_name,
  877. const char *method_name,
  878. void *function,
  879. GDExtensionVariantType return_type);
  880. // Version for 1 argument, no return.
  881. void bind_method_1(
  882. const char *class_name,
  883. const char *method_name,
  884. void *function,
  885. const char *arg1_name,
  886. GDExtensionVariantType arg1_type);
  887. Then switch back to the ``api.c`` file to implement these:
  888. .. code-block:: c
  889. // Version for 0 arguments, with return.
  890. void bind_method_0_r(
  891. const char *class_name,
  892. const char *method_name,
  893. void *function,
  894. GDExtensionVariantType return_type)
  895. {
  896. StringName method_name_string;
  897. constructors.string_name_new_with_latin1_chars(&method_name_string, method_name, false);
  898. GDExtensionClassMethodCall call_func = call_0_args_ret_float;
  899. GDExtensionClassMethodPtrCall ptrcall_func = ptrcall_0_args_ret_float;
  900. GDExtensionPropertyInfo return_info = make_property(return_type, "");
  901. GDExtensionClassMethodInfo method_info = {
  902. .name = &method_name_string,
  903. .method_userdata = function,
  904. .call_func = call_func,
  905. .ptrcall_func = ptrcall_func,
  906. .method_flags = GDEXTENSION_METHOD_FLAGS_DEFAULT,
  907. .has_return_value = true,
  908. .return_value_info = &return_info,
  909. .return_value_metadata = GDEXTENSION_METHOD_ARGUMENT_METADATA_NONE,
  910. .argument_count = 0,
  911. };
  912. StringName class_name_string;
  913. constructors.string_name_new_with_latin1_chars(&class_name_string, class_name, false);
  914. api.classdb_register_extension_class_method(class_library, &class_name_string, &method_info);
  915. // Destruct things.
  916. destructors.string_name_destructor(&method_name_string);
  917. destructors.string_name_destructor(&class_name_string);
  918. destruct_property(&return_info);
  919. }
  920. // Version for 1 argument, no return.
  921. void bind_method_1(
  922. const char *class_name,
  923. const char *method_name,
  924. void *function,
  925. const char *arg1_name,
  926. GDExtensionVariantType arg1_type)
  927. {
  928. StringName method_name_string;
  929. constructors.string_name_new_with_latin1_chars(&method_name_string, method_name, false);
  930. GDExtensionClassMethodCall call_func = call_1_float_arg_no_ret;
  931. GDExtensionClassMethodPtrCall ptrcall_func = ptrcall_1_float_arg_no_ret;
  932. GDExtensionPropertyInfo args_info[] = {
  933. make_property(arg1_type, arg1_name),
  934. };
  935. GDExtensionClassMethodArgumentMetadata args_metadata[] = {
  936. GDEXTENSION_METHOD_ARGUMENT_METADATA_NONE,
  937. };
  938. GDExtensionClassMethodInfo method_info = {
  939. .name = &method_name_string,
  940. .method_userdata = function,
  941. .call_func = call_func,
  942. .ptrcall_func = ptrcall_func,
  943. .method_flags = GDEXTENSION_METHOD_FLAGS_DEFAULT,
  944. .has_return_value = false,
  945. .argument_count = 1,
  946. .arguments_info = args_info,
  947. .arguments_metadata = args_metadata,
  948. };
  949. StringName class_name_string;
  950. constructors.string_name_new_with_latin1_chars(&class_name_string, class_name, false);
  951. api.classdb_register_extension_class_method(class_library, &class_name_string, &method_info);
  952. // Destruct things.
  953. destructors.string_name_destructor(&method_name_string);
  954. destructors.string_name_destructor(&class_name_string);
  955. destruct_property(&args_info[0]);
  956. }
  957. Both functions are very similar. First, they create a ``StringName`` with the
  958. method name. This is created in the stack since we don't need to keep it after
  959. the function ends. Then they create local variables to hold the ``call_func``
  960. and ``ptrcall_func``, pointing to the helper functions we defined earlier.
  961. In the next step they diverge a bit. The first one creates a property for the
  962. return value, which has an empty name since it's not needed. The other creates
  963. an array of properties for the arguments, which in this case has a single
  964. element. This one also has an array of metadata, which can be used if there's
  965. something special about the argument (e.g. if an ``int`` value is 32 bits long
  966. instead of the default of 64 bits).
  967. Afterwards, they create the ``GDExtensionClassMethodInfo`` with the required
  968. fields for each case. Then they make a ``StringName`` for the class name, in
  969. order to associate the method with the class. Next, they call the API function
  970. to actually bind this method to the class. Finally, we destruct the objects we
  971. created since they aren't needed anymore.
  972. .. note::
  973. The bind helpers here use the call helpers we created earlier, so do note that
  974. those call helpers only accept the Godot ``FLOAT`` type (which is equivalent to
  975. ``double`` in C). If you intend to use this for other types, you would need to
  976. check the type of the arguments and return type and select an appropriate
  977. function callback. This is avoided here only to keep the example from becoming
  978. even longer.
  979. Now that we have the means to bind methods, we can actually do so in our custom
  980. class. Go to the ``gdexample.c`` file and fill up the
  981. ``gdexample_class_bind_methods()`` function:
  982. .. code-block:: c
  983. void gdexample_class_bind_methods()
  984. {
  985. bind_method_0_r("GDExample", "get_amplitude", gdexample_class_get_amplitude, GDEXTENSION_VARIANT_TYPE_FLOAT);
  986. bind_method_1("GDExample", "set_amplitude", gdexample_class_set_amplitude, "amplitude", GDEXTENSION_VARIANT_TYPE_FLOAT);
  987. bind_method_0_r("GDExample", "get_speed", gdexample_class_get_speed, GDEXTENSION_VARIANT_TYPE_FLOAT);
  988. bind_method_1("GDExample", "set_speed", gdexample_class_set_speed, "speed", GDEXTENSION_VARIANT_TYPE_FLOAT);
  989. }
  990. Since this function is already being called by the initialization process, we
  991. can stop here. This function is much more straightforward after we created all the
  992. infrastructure to make this work. You can see that implementing the binding
  993. functions inline here would take some space and also be quite repetitive. This
  994. also makes it easier to add another method in the future.
  995. If you compile the code and reopen the demo project, nothing will be different
  996. at first, since we only added two new methods. To ensure those are registered
  997. properly, you can search for ``GDExample`` in the editor help and verify they
  998. are present in the documentation page.
  999. .. image:: img/gdextension_c_methods_doc.webp
  1000. Custom properties
  1001. -----------------
  1002. Since we now have the getter and setter for our properties already bound, we can
  1003. move forward to create actual properties that will be displayed in the Godot
  1004. editor inspector.
  1005. Given our extensive setup in the previous section, there are only a few things
  1006. needed to enable us to bind properties. First, let's get a new API function in
  1007. the ``api.h`` file:
  1008. .. code-block:: c
  1009. struct API {
  1010. ...
  1011. GDExtensionInterfaceClassdbRegisterExtensionClassProperty classdb_register_extension_class_property;
  1012. } api;
  1013. Let's also declare a function here to bind properties:
  1014. .. code-block:: c
  1015. void bind_property(
  1016. const char *class_name,
  1017. const char *name,
  1018. GDExtensionVariantType type,
  1019. const char *getter,
  1020. const char *setter);
  1021. In the ``api.c`` file, we can load the new API function:
  1022. .. code-block:: c
  1023. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  1024. {
  1025. // API
  1026. ...
  1027. api.classdb_register_extension_class_property = p_get_proc_address("classdb_register_extension_class_property");
  1028. ...
  1029. }
  1030. Then we can implement our new helper function in this same file:
  1031. .. code-block:: c
  1032. void bind_property(
  1033. const char *class_name,
  1034. const char *name,
  1035. GDExtensionVariantType type,
  1036. const char *getter,
  1037. const char *setter)
  1038. {
  1039. StringName class_string_name;
  1040. constructors.string_name_new_with_latin1_chars(&class_string_name, class_name, false);
  1041. GDExtensionPropertyInfo info = make_property(type, name);
  1042. StringName getter_name;
  1043. constructors.string_name_new_with_latin1_chars(&getter_name, getter, false);
  1044. StringName setter_name;
  1045. constructors.string_name_new_with_latin1_chars(&setter_name, setter, false);
  1046. api.classdb_register_extension_class_property(class_library, &class_string_name, &info, &setter_name, &getter_name);
  1047. // Destruct things.
  1048. destructors.string_name_destructor(&class_string_name);
  1049. destruct_property(&info);
  1050. destructors.string_name_destructor(&getter_name);
  1051. destructors.string_name_destructor(&setter_name);
  1052. }
  1053. This function is similar to the one for binding methods. The main difference is
  1054. that we don't need an extra struct since we can simply use the
  1055. ``GDExtensionPropertyInfo`` that is created by our helper function, so it's more
  1056. straightforward. It only creates the ``StringName`` values from the
  1057. C strings, creates a property info struct using our helper, calls the API
  1058. function to register the property in the class and then destructs all the objects
  1059. we created.
  1060. With this done, we can extend the ``gdexample_class_bind_methods()`` function in the
  1061. ``gdexample.c`` file:
  1062. .. code-block:: c
  1063. void gdexample_class_bind_methods()
  1064. {
  1065. bind_method_0_r("GDExample", "get_amplitude", gdexample_class_get_amplitude, GDEXTENSION_VARIANT_TYPE_FLOAT);
  1066. bind_method_1("GDExample", "set_amplitude", gdexample_class_set_amplitude, "amplitude", GDEXTENSION_VARIANT_TYPE_FLOAT);
  1067. bind_property("GDExample", "amplitude", GDEXTENSION_VARIANT_TYPE_FLOAT, "get_amplitude", "set_amplitude");
  1068. bind_method_0_r("GDExample", "get_speed", gdexample_class_get_speed, GDEXTENSION_VARIANT_TYPE_FLOAT);
  1069. bind_method_1("GDExample", "set_speed", gdexample_class_set_speed, "speed", GDEXTENSION_VARIANT_TYPE_FLOAT);
  1070. bind_property("GDExample", "speed", GDEXTENSION_VARIANT_TYPE_FLOAT, "get_speed", "set_speed");
  1071. }
  1072. If you build the extension with ``scons``, you'll see in the Godot editor the new property shown
  1073. not only on the documentation page for the custom class but also in the Inspector dock when the
  1074. ``GDExample`` node is selected.
  1075. .. image:: img/gdextension_c_inspector_properties.webp
  1076. Binding virtual methods
  1077. -----------------------
  1078. Our custom node now has properties to influence how it operates, but it still
  1079. doesn't do anything. In this section, we will bind the virtual method
  1080. :ref:`_process() <class_Node_private_method__process>` and make our custom sprite
  1081. move a little bit.
  1082. In the ``gdexample.h`` file, let's add a function that represents the custom
  1083. ``_process()`` method:
  1084. .. code-block:: c
  1085. // Methods.
  1086. void gdexample_class_process(GDExample *self, double delta);
  1087. We'll also add a "private" field to keep track of the time passed in our custom
  1088. struct. This is "private" only in the sense that it won't be bound to the Godot
  1089. API, even though it is public in the C side, given the language lacks access
  1090. modifiers.
  1091. .. code-block:: c
  1092. typedef struct
  1093. {
  1094. // Private properties.
  1095. double time_passed;
  1096. ...
  1097. } GDExample;
  1098. On the counterpart source file ``gdexample.c`` we need to initialize the new
  1099. field in the constructor:
  1100. .. code-block:: c
  1101. void gdexample_class_constructor(GDExample *self)
  1102. {
  1103. self->time_passed = 0.0;
  1104. self->amplitude = 10.0;
  1105. self->speed = 1.0;
  1106. }
  1107. Then we can create the simplest implementation for the ``_process`` method:
  1108. .. code-block:: c
  1109. void gdexample_class_process(GDExample *self, double delta)
  1110. {
  1111. self->time_passed += self->speed * delta;
  1112. }
  1113. For now it will do nothing but update the private field we created. We'll come
  1114. back to this after the method is properly bound.
  1115. Virtual methods are a bit different from the regular bindings. Instead of
  1116. explicitly registering the method itself, we'll register a special function that
  1117. Godot will call to ask if a particular virtual method is implemented in our
  1118. extension. The engine will pass a ``StringName`` as an argument so, following
  1119. the spirit of this tutorial, we'll create a helper function to check if it is
  1120. equal to a C string.
  1121. Let's add the declaration to the ``api.h`` file:
  1122. .. code-block:: c
  1123. // Compare a StringName with a C string.
  1124. bool is_string_name_equal(GDExtensionConstStringNamePtr p_a, const char *p_b);
  1125. We'll also add a new struct to this file, to hold function pointers for custom operators:
  1126. .. code-block:: c
  1127. struct Operators
  1128. {
  1129. GDExtensionPtrOperatorEvaluator string_name_equal;
  1130. } operators;
  1131. Then in the ``api.c`` file we'll load the function pointer from the API:
  1132. .. code-block:: c
  1133. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  1134. {
  1135. // Get helper functions first.
  1136. ...
  1137. GDExtensionInterfaceVariantGetPtrOperatorEvaluator variant_get_ptr_operator_evaluator = (GDExtensionInterfaceVariantGetPtrOperatorEvaluator)p_get_proc_address("variant_get_ptr_operator_evaluator");
  1138. ...
  1139. // Operators.
  1140. operators.string_name_equal = variant_get_ptr_operator_evaluator(GDEXTENSION_VARIANT_OP_EQUAL, GDEXTENSION_VARIANT_TYPE_STRING_NAME, GDEXTENSION_VARIANT_TYPE_STRING_NAME);
  1141. }
  1142. As you can see we need a new local helper here in order to grab the function
  1143. pointer for the operator.
  1144. With this handy, we can easily create our comparison function in the same file:
  1145. .. code-block:: c
  1146. bool is_string_name_equal(GDExtensionConstStringNamePtr p_a, const char *p_b)
  1147. {
  1148. // Create a StringName for the C string.
  1149. StringName string_name;
  1150. constructors.string_name_new_with_latin1_chars(&string_name, p_b, false);
  1151. // Compare both StringNames.
  1152. bool is_equal = false;
  1153. operators.string_name_equal(p_a, &string_name, &is_equal);
  1154. // Destroy the created StringName.
  1155. destructors.string_name_destructor(&string_name);
  1156. // Return the result.
  1157. return is_equal;
  1158. }
  1159. This function creates a ``StringName`` from the argument, compares with
  1160. the other one using the operator function pointer, and returns the result. Note
  1161. that the return value for the operator is passed as an out reference, this is a
  1162. common thing in the API.
  1163. Let's go back to the ``gdexample.h`` file and add a couple of functions that
  1164. will be used as the callbacks for the Godot API:
  1165. .. code-block:: c
  1166. void *gdexample_class_get_virtual_with_data(void *p_class_userdata, GDExtensionConstStringNamePtr p_name);
  1167. void gdexample_class_call_virtual_with_data(GDExtensionClassInstancePtr p_instance, GDExtensionConstStringNamePtr p_name, void *p_virtual_call_userdata, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr r_ret);
  1168. There are actually two ways of registering virtual methods. Only one has the
  1169. ``get`` part, in which you give Godot a properly crafted function pointer which
  1170. will be called. For this we would need to create another helper for each virtual
  1171. method, something that is not very convenient. Instead, we use the second method
  1172. which allows us to return any data, and then Godot will call a second callback
  1173. and give us back this data along with the call information. We can simply give
  1174. our own function pointer as custom data and then have a single callback for all
  1175. virtual methods. Although in this example we will only use it for one method,
  1176. this way is simpler to expand.
  1177. So let's implement those two functions in the ``gdexample.c`` file:
  1178. .. code-block:: c
  1179. void *gdexample_class_get_virtual_with_data(void *p_class_userdata, GDExtensionConstStringNamePtr p_name)
  1180. {
  1181. // If it is the "_process" method, return a pointer to the gdexample_class_process function.
  1182. if (is_string_name_equal(p_name, "_process"))
  1183. {
  1184. return (void *)gdexample_class_process;
  1185. }
  1186. // Otherwise, return NULL.
  1187. return NULL;
  1188. }
  1189. void gdexample_class_call_virtual_with_data(GDExtensionClassInstancePtr p_instance, GDExtensionConstStringNamePtr p_name, void *p_virtual_call_userdata, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr r_ret)
  1190. {
  1191. // If it is the "_process" method, call it with a helper.
  1192. if (p_virtual_call_userdata == &gdexample_class_process)
  1193. {
  1194. ptrcall_1_float_arg_no_ret(p_virtual_call_userdata, p_instance, p_args, r_ret);
  1195. }
  1196. }
  1197. Those functions are also quite straightforward after making all the helpers
  1198. previously.
  1199. For the first one, we simply check if the function name requested is
  1200. ``_process`` and if it is we return a function pointer to our implementation of
  1201. it. Otherwise we return ``NULL``, signaling that the method is not being
  1202. overridden. We don't use the ``p_class_userdata`` here since this function is
  1203. meant only for one class and we don't have any data associated with it.
  1204. The second one is similar. If it is the ``_process()`` method, it uses the given
  1205. function pointer to call the ``ptrcall`` helper, passing the call arguments
  1206. forward. Otherwise it simply does nothing, since we don't have any other virtual
  1207. methods being implemented.
  1208. The only thing missing is using those callbacks when the class is registered. Go
  1209. to the ``init.c`` file and change the ``class_info`` initialization to include
  1210. those, replacing the ``NULL`` value used previously:
  1211. .. code-block:: c
  1212. void initialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level)
  1213. {
  1214. ...
  1215. GDExtensionClassCreationInfo2 class_info = {
  1216. ...
  1217. .get_virtual_call_data_func = gdexample_class_get_virtual_with_data,
  1218. .call_virtual_with_data_func = gdexample_class_call_virtual_with_data,
  1219. ...
  1220. };
  1221. ...
  1222. }
  1223. This is enough to bind the virtual method. If you build the extension and run
  1224. the demo project again, the ``_process()`` function will be called. You just won't
  1225. be able to tell since the function itself does nothing visible. We will solve
  1226. this now by making the custom node move following a pattern.
  1227. In order to make our node do stuff, we'll need to call Godot methods. Not only
  1228. the GDExtension API functions as we've being doing so far, but actual engine
  1229. methods, as we would do with scripting. This naturally requires some extra setup.
  1230. First, let's add :ref:`class_Vector2` to our ``defs.h`` file, so we
  1231. can use it in our method:
  1232. .. code-block:: c
  1233. // The sizes can be obtained from the extension_api.json file.
  1234. ...
  1235. #ifdef REAL_T_IS_DOUBLE
  1236. #define VECTOR2_SIZE 16
  1237. #else
  1238. #define VECTOR2_SIZE 8
  1239. #endif
  1240. ...
  1241. // Types.
  1242. ...
  1243. typedef struct
  1244. {
  1245. uint8_t data[VECTOR2_SIZE];
  1246. } Vector2;
  1247. The ``REAL_T_IS_DOUBLE`` define is only needed if your Godot version was built
  1248. with double precision support, which is not the default.
  1249. Now, in the ``api.h`` file, we'll add few things to the API structs, including a
  1250. new one for holding engine methods to call.
  1251. .. code-block:: c
  1252. struct Constructors
  1253. {
  1254. ...
  1255. GDExtensionPtrConstructor vector2_constructor_x_y;
  1256. } constructors;
  1257. ...
  1258. struct Methods
  1259. {
  1260. GDExtensionMethodBindPtr node2d_set_position;
  1261. } methods;
  1262. struct API
  1263. {
  1264. ...
  1265. GDExtensionInterfaceClassdbGetMethodBind classdb_get_method_bind;
  1266. GDExtensionInterfaceObjectMethodBindPtrcall object_method_bind_ptrcall;
  1267. } api;
  1268. Then in the ``api.c`` file we can grab the function pointers from Godot:
  1269. .. code-block::
  1270. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  1271. {
  1272. // Get helper functions first.
  1273. ...
  1274. GDExtensionInterfaceVariantGetPtrConstructor variant_get_ptr_constructor = (GDExtensionInterfaceVariantGetPtrConstructor)p_get_proc_address("variant_get_ptr_constructor");
  1275. // API.
  1276. ...
  1277. api.classdb_get_method_bind = (GDExtensionInterfaceClassdbGetMethodBind)p_get_proc_address("classdb_get_method_bind");
  1278. api.object_method_bind_ptrcall = p_get_proc_address("object_method_bind_ptrcall");
  1279. // Constructors.
  1280. ...
  1281. constructors.vector2_constructor_x_y = variant_get_ptr_constructor(GDEXTENSION_VARIANT_TYPE_VECTOR2, 3); // See extension_api.json for indices.
  1282. ...
  1283. }
  1284. The only noteworthy part here is the ``Vector2`` constructor, for which we request the
  1285. index ``3``. Since there are multiple constructors with different kinds of
  1286. arguments, we need to specify which one we want. In this case we're getting the
  1287. one that takes two float numbers as the ``x`` and ``y`` coordinates, hence the
  1288. name. This index can be retrieved from the ``extension_api.json`` file. Note we
  1289. also need a new local helper to get it.
  1290. Be aware that we don't get anything for the methods struct here. This is because
  1291. this function is called too early in the initialization process, so classes
  1292. won't be properly registered yet.
  1293. Instead, we're gonna use the initialization level callback to grab those when we
  1294. are registering our custom class. Add this to the ``init.c`` file:
  1295. .. code-block:: c
  1296. void initialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level)
  1297. {
  1298. if (p_level != GDEXTENSION_INITIALIZATION_SCENE)
  1299. {
  1300. return;
  1301. }
  1302. // Get ClassDB methods here because the classes we need are all properly registered now.
  1303. // See extension_api.json for hashes.
  1304. StringName native_class_name;
  1305. StringName method_name;
  1306. constructors.string_name_new_with_latin1_chars(&native_class_name, "Node2D", false);
  1307. constructors.string_name_new_with_latin1_chars(&method_name, "set_position", false);
  1308. methods.node2d_set_position = api.classdb_get_method_bind(&native_class_name, &method_name, 743155724);
  1309. destructors.string_name_destructor(&native_class_name);
  1310. destructors.string_name_destructor(&method_name);
  1311. ...
  1312. }
  1313. Here we create ``StringName``'s for the class and method we want to get, then use
  1314. the GDExtension API to retrieve their ``MethodBind``, which is an object that
  1315. represents the bound method. We get the ``set_position`` method from ``Node2D``
  1316. since this is where it was registered, even though we're going to use it in a
  1317. ``Sprite2D``, a derived class.
  1318. The seemingly random number for getting the bind is actually a hash of the
  1319. method signature. This allows Godot to match the method you're requesting even
  1320. if in a future Godot version this signature changes, by providing a
  1321. compatibility method that matches what you're asking for. This is one of the
  1322. systems that allow the engine to load extensions made for previous versions. You
  1323. can get the value of this hash from the ``extension_api.json`` file.
  1324. With all that, we can finally implement our custom ``_process()`` method in the
  1325. ``gdexample.c`` file:
  1326. .. code-block:: c
  1327. ...
  1328. #include <math.h>
  1329. ...
  1330. void gdexample_class_process(GDExample *self, double delta)
  1331. {
  1332. self->time_passed += self->speed * delta;
  1333. Vector2 new_position;
  1334. // Set up the arguments for the Vector2 constructor.
  1335. double x = self->amplitude + (self->amplitude * sin(self->time_passed * 2.0));
  1336. double y = self->amplitude + (self->amplitude * cos(self->time_passed * 1.5));
  1337. GDExtensionConstTypePtr args[] = {&x, &y};
  1338. // Call the Vector2 constructor.
  1339. constructors.vector2_constructor_x_y(&new_position, args);
  1340. // Set up the arguments for the set_position method.
  1341. GDExtensionConstTypePtr args2[] = {&new_position};
  1342. // Call the set_position method.
  1343. api.object_method_bind_ptrcall(methods.node2d_set_position, self->object, args2, NULL);
  1344. }
  1345. After updating the time passed scaled by the ``speed`` property, it creates
  1346. ``x`` and ``y`` values based on that, also modulated by the ``amplitude``
  1347. property. This is what will give the pattern effect. The ``math.h`` header is
  1348. needed for the ``sin()`` and ``cos()`` functions used here.
  1349. Then it sets up an array of arguments to construct a ``Vector2``, followed by
  1350. calling the constructor. It sets up another array of arguments and use it to
  1351. call the ``set_position()`` method via the bind we acquired previously.
  1352. Since nothing here allocates any memory, there's not a need to cleanup.
  1353. Now we can build the extension again and reopen Godot. Even in the editor you'll
  1354. see the custom sprite moving.
  1355. .. image:: img/gdextension_c_moving_sprite.gif
  1356. Try changing the **Speed** and **Amplitude** properties and see how the sprite
  1357. react.
  1358. Registering and emitting a signal
  1359. ---------------------------------
  1360. To complete this tutorial, let's see how you can register a custom signal and
  1361. emit it when appropriate. As you might have guessed, we'll need a few more
  1362. function pointers from the API and more helper functions.
  1363. In the ``api.h`` file we're adding two things. One is an API function to
  1364. register a signal, the other is a helper function to wrap the signal binding.
  1365. .. code-block:: c
  1366. struct API
  1367. {
  1368. ...
  1369. GDExtensionInterfaceClassdbRegisterExtensionClassSignal classdb_register_extension_class_signal;
  1370. } api;
  1371. ...
  1372. // Version for 1 argument.
  1373. void bind_signal_1(
  1374. const char *class_name,
  1375. const char *signal_name,
  1376. const char *arg1_name,
  1377. GDExtensionVariantType arg1_type);
  1378. In this case we only have a version for one argument, since it's what we're
  1379. going to use.
  1380. Moving to the ``api.c`` file, we can load this new function pointer and
  1381. implement the helper:
  1382. .. code-block:: c
  1383. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  1384. {
  1385. // API.
  1386. ...
  1387. api.classdb_register_extension_class_signal = p_get_proc_address("classdb_register_extension_class_signal");
  1388. ...
  1389. }
  1390. void bind_signal_1(
  1391. const char *class_name,
  1392. const char *signal_name,
  1393. const char *arg1_name,
  1394. GDExtensionVariantType arg1_type)
  1395. {
  1396. StringName class_string_name;
  1397. constructors.string_name_new_with_latin1_chars(&class_string_name, class_name, false);
  1398. StringName signal_string_name;
  1399. constructors.string_name_new_with_latin1_chars(&signal_string_name, signal_name, false);
  1400. GDExtensionPropertyInfo args_info[] = {
  1401. make_property(arg1_type, arg1_name),
  1402. };
  1403. api.classdb_register_extension_class_signal(class_library, &class_string_name, &signal_string_name, args_info, 1);
  1404. // Destruct things.
  1405. destructors.string_name_destructor(&class_string_name);
  1406. destructors.string_name_destructor(&signal_string_name);
  1407. destruct_property(&args_info[0]);
  1408. }
  1409. This one is very similar to the function to bind methods. The main difference is
  1410. that we don't need to fill another struct, we just pass the needed names and the
  1411. array of arguments. The ``1`` at the end means the amount of arguments the
  1412. signal provides.
  1413. With this we can bind the signal in ``gdexample.c``:
  1414. .. code-block:: c
  1415. void gdexample_class_bind_methods()
  1416. {
  1417. ...
  1418. bind_signal_1("GDExample", "position_changed", "new_position", GDEXTENSION_VARIANT_TYPE_VECTOR2);
  1419. }
  1420. In order to emit a signal, we need to call the
  1421. :ref:`emit_signal() <class_Object_method_emit_signal>` method on our custom node.
  1422. Since this is a ``vararg`` function (meaning it takes any amount of arguments),
  1423. we cannot use ``ptrcall``. To do a regular call, we have to create Variants,
  1424. which require a few more steps of plumbing to get done.
  1425. First, in the ``defs.h`` file we create a definition for Variant:
  1426. .. code-block:: c
  1427. ...
  1428. // The sizes can be obtained from the extension_api.json file.
  1429. ...
  1430. #ifdef REAL_T_IS_DOUBLE
  1431. #define VARIANT_SIZE 40
  1432. #define VECTOR2_SIZE 16
  1433. #else
  1434. #define VARIANT_SIZE 24
  1435. #define VECTOR2_SIZE 8
  1436. #endif
  1437. ...
  1438. // Types.
  1439. ...
  1440. typedef struct
  1441. {
  1442. uint8_t data[VARIANT_SIZE];
  1443. } Variant;
  1444. We first set the size of Variant together with the size of Vector2 that we added
  1445. before. Then we use it to create an opaque struct that is enough to hold the
  1446. Variant data. Again, we set the size for double precision builds as a fallback,
  1447. since by the official Godot builds use single precision.
  1448. The ``emit_signal()`` function will be called with two arguments. The first is
  1449. the name of the signal to be emitted and the second is the argument we're
  1450. passing to the signal connections, which is a Vector2 as we declared when
  1451. binding it. So we're gonna create a helper function that can call a MethodBind
  1452. with these types. Even though it does return something (an error code), we don't
  1453. need to deal with it, so for now we're just going to ignore it.
  1454. In the ``api.h``, we're adding a few things to the existing structs, plus a new
  1455. helper function for the call:
  1456. .. code-block:: c
  1457. struct Constructors
  1458. {
  1459. ...
  1460. GDExtensionVariantFromTypeConstructorFunc variant_from_string_name_constructor;
  1461. GDExtensionVariantFromTypeConstructorFunc variant_from_vector2_constructor;
  1462. } constructors;
  1463. struct Destructors
  1464. {
  1465. ..
  1466. GDExtensionInterfaceVariantDestroy variant_destroy;
  1467. } destructors;
  1468. ...
  1469. struct Methods
  1470. {
  1471. ...
  1472. GDExtensionMethodBindPtr object_emit_signal;
  1473. } methods;
  1474. struct API
  1475. {
  1476. ...
  1477. GDExtensionInterfaceObjectMethodBindCall object_method_bind_call;
  1478. } api;
  1479. ...
  1480. // Helper to call with Variant arguments.
  1481. void call_2_args_stringname_vector2_no_ret_variant(
  1482. GDExtensionMethodBindPtr p_method_bind,
  1483. GDExtensionObjectPtr p_instance,
  1484. const GDExtensionTypePtr p_arg1,
  1485. const GDExtensionTypePtr p_arg2);
  1486. Now let's switch to the ``api.c`` file to load these new function pointers and
  1487. implement the helper function.
  1488. .. code-block:: c
  1489. void load_api(GDExtensionInterfaceGetProcAddress p_get_proc_address)
  1490. {
  1491. // API.
  1492. ...
  1493. api.object_method_bind_call = p_get_proc_address("object_method_bind_call");
  1494. // Constructors.
  1495. ...
  1496. constructors.variant_from_string_name_constructor = api.get_variant_from_type_constructor(GDEXTENSION_VARIANT_TYPE_STRING_NAME);
  1497. constructors.variant_from_vector2_constructor = api.get_variant_from_type_constructor(GDEXTENSION_VARIANT_TYPE_VECTOR2);
  1498. // Destructors.
  1499. ...
  1500. destructors.variant_destroy = p_get_proc_address("variant_destroy");
  1501. ...
  1502. }
  1503. ...
  1504. void call_2_args_stringname_vector2_no_ret_variant(GDExtensionMethodBindPtr p_method_bind, GDExtensionObjectPtr p_instance, const GDExtensionTypePtr p_arg1, const GDExtensionTypePtr p_arg2)
  1505. {
  1506. // Set up the arguments for the call.
  1507. Variant arg1;
  1508. constructors.variant_from_string_name_constructor(&arg1, p_arg1);
  1509. Variant arg2;
  1510. constructors.variant_from_vector2_constructor(&arg2, p_arg2);
  1511. GDExtensionConstVariantPtr args[] = {&arg1, &arg2};
  1512. // Add dummy return value storage.
  1513. Variant ret;
  1514. // Call the function.
  1515. api.object_method_bind_call(p_method_bind, p_instance, args, 2, &ret, NULL);
  1516. // Destroy the arguments that need it.
  1517. destructors.variant_destroy(&arg1);
  1518. destructors.variant_destroy(&ret);
  1519. }
  1520. This helper function has some boilerplate code but is quite straightforward. It sets up the
  1521. two arguments inside stack allocated Variants, then creates an array with
  1522. pointers to those. It also sets up another Variant to keep the return value,
  1523. which we don't need to construct since the call expects it to be uninitialized.
  1524. Then it actually calls the MethodBind using the instance we provided and the
  1525. arguments. The ``NULL`` at the end would be a pointer to a
  1526. ``GDExtensionCallError`` struct. This can be used to treat potential errors when
  1527. calling the functions (such as wrong arguments). For the sake of simplicity
  1528. we're not gonna handle that here.
  1529. At the end we need to destruct the Variants we created. While technically the
  1530. Vector2 one does not require destructing, it is clearer to cleanup everything.
  1531. We also need to load the MethodBind, which we'll do in the ``init.c`` file,
  1532. right after loading the one for the ``set_position`` method we did before:
  1533. .. code-block:: c
  1534. void initialize_gdexample_module(void *p_userdata, GDExtensionInitializationLevel p_level)
  1535. {
  1536. ...
  1537. constructors.string_name_new_with_latin1_chars(&native_class_name, "Object", false);
  1538. constructors.string_name_new_with_latin1_chars(&method_name, "emit_signal", false);
  1539. methods.object_emit_signal = api.classdb_get_method_bind(&native_class_name, &method_name, 4047867050);
  1540. destructors.string_name_destructor(&native_class_name);
  1541. destructors.string_name_destructor(&method_name);
  1542. // Register class.
  1543. ...
  1544. }
  1545. Note that we reuse the ``native_class_name`` and ``method_name`` variables here,
  1546. so we don't need to declare new ones.
  1547. Now go to the ``gdexample.h`` file where we're going to add a couple of fields:
  1548. .. code-block:: c
  1549. typedef struct
  1550. {
  1551. // Private properties.
  1552. ..
  1553. double time_emit;
  1554. ..
  1555. // Metadata.
  1556. StringName position_changed; // For signal.
  1557. } GDExample;
  1558. The first one will store the time passed since the last signal was emitted,
  1559. since we'll be doing so at regular intervals. The other is just to cache the
  1560. signal name so we don't need to create a new StringName every time.
  1561. In the source ``gdexample.c`` file we can change the constructor and destructor
  1562. to deal with the new fields:
  1563. .. code-block:: c
  1564. void gdexample_class_constructor(GDExample *self)
  1565. {
  1566. ...
  1567. self->time_emit = 0.0;
  1568. // Construct the StringName for the signal.
  1569. constructors.string_name_new_with_latin1_chars(&self->position_changed, "position_changed", false);
  1570. }
  1571. void gdexample_class_destructor(GDExample *self)
  1572. {
  1573. // Destruct the StringName for the signal.
  1574. destructors.string_name_destructor(&self->position_changed);
  1575. }
  1576. It is important to destruct the StringName to avoid memory leaks.
  1577. Now we can add to the ``gdexample_class_process()`` function to actually emit the
  1578. signal:
  1579. .. code-block:: c
  1580. void gdexample_class_process(GDExample *self, double delta)
  1581. {
  1582. ...
  1583. self->time_emit += delta;
  1584. if (self->time_emit >= 1.0)
  1585. {
  1586. // Call the emit_signal method.
  1587. call_2_args_stringname_vector2_no_ret_variant(methods.object_emit_signal, self->object, &self->position_changed, &new_position);
  1588. self->time_emit = 0.0;
  1589. }
  1590. }
  1591. This updates the time passed for the signal emission and, if it is over one
  1592. second it calls the ``emit_signal()`` function on the current instance, passing
  1593. the name of the signal and the new position as arguments.
  1594. Now we're done with our C GDExtension. Build it once more and reopen the demo
  1595. project in the editor.
  1596. In the documentation page for ``GDExample`` you can see the new signal we bound:
  1597. .. image:: img/gdextension_c_signal_doc.webp
  1598. To check it's working, let's add a small script to the root node, parent of our
  1599. custom one, that prints the position to the output every time it receives the
  1600. signal:
  1601. .. code-block:: gdscript
  1602. extends Node2D
  1603. func _ready():
  1604. $GDExample.position_changed.connect(on_position_changed)
  1605. func on_position_changed(new_position):
  1606. prints("New position:", new_position)
  1607. Run the project and you can observe the values being printed in the Output dock
  1608. in the editor:
  1609. .. image:: img/gdextension_c_signal_print.webp
  1610. Conclusion
  1611. ----------
  1612. This tutorial shows a basic extension with custom methods, properties, and
  1613. signals. While it does require a good amount of boilerplate, it can scale well
  1614. by creating helper functions to handle the tedious tasks.
  1615. This should serve as a good basis to understand the GDExtension API and as a
  1616. starting point to create custom binding generators. In fact, it would be
  1617. possible to create bindings for C using such type of generator, making the
  1618. actual coding look more like the ``gdexample.c`` file in this example, which is
  1619. quite straightforward and not very verbose.
  1620. If you want to create actual extensions, it is preferred to use the C++ bindings
  1621. instead, as it takes away all of the boilerplate from your code. Check the
  1622. :ref:`godot-cpp documentation <doc_godot_cpp>` to see how you can
  1623. do this.