gdnative_c_example.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. .. _doc_gdnative_c_example:
  2. GDNative C example
  3. ==================
  4. Introduction
  5. ------------
  6. This tutorial will introduce you to the bare minimum required to create GDNative
  7. modules. This should be your starting point into the world of GDNative.
  8. Understanding the contents of this tutorial will help you in understanding all
  9. that is to come after this.
  10. Before we begin, you can download the source code to the example object we
  11. describe below in the `GDNative-demos repository
  12. <https://github.com/godotengine/gdnative-demos/tree/master/c/simple>`_.
  13. This example project also contains a SConstruct file that makes compiling a
  14. little easier, but in this tutorial we'll be doing things by hand to
  15. understand the process.
  16. :ref:`GDNative <class_GDNative>` can be used to create several types of
  17. additions to Godot, using interfaces such as
  18. :ref:`PluginScript <class_PluginScript>` or
  19. :ref:`ARVRInterfaceGDNative <class_ARVRInterfaceGDNative>`. In this tutorial we
  20. are going to look at creating a :ref:`NativeScript <class_NativeScript>`
  21. module. NativeScript allows you to write logic in C or C++ in a similar fashion
  22. as you would write a GDScript file. We'll be creating the C equivalent of this
  23. GDScript:
  24. ::
  25. extends Reference
  26. var data
  27. func _ready():
  28. data = "World from GDScript!"
  29. func get_data():
  30. return data
  31. Future tutorials will focus on the other types of GDNative modules and explain
  32. when and how to use each of them.
  33. Prerequisites
  34. -------------
  35. Before we start you'll need a few things:
  36. 1) A Godot executable for your target version.
  37. 2) A C compiler. On Linux, install ``gcc`` or ``clang`` from your package
  38. manager. On macOS, you can install Xcode from the Mac App Store. On Windows,
  39. you can use Visual Studio 2015 or later, or MinGW-w64.
  40. 3) A Git clone of the `godot-headers
  41. repository <https://github.com/godotengine/godot-headers.git>`_: these are
  42. the C headers for Godot's public API exposed to GDNative.
  43. For the latter, we suggest that you create a dedicated folder for this GDNative
  44. example project, open a terminal in that folder and execute:
  45. .. code-block:: none
  46. git clone https://github.com/godotengine/godot-headers.git
  47. This will download the required files into that folder.
  48. .. tip::
  49. If you plan to use Git for your GDNative project, you can also add
  50. ``godot-headers`` as a Git submodule.
  51. .. note::
  52. The ``godot-headers`` repository has different branches. As Godot evolves,
  53. so does GDNative. While we try to preserve compatibility between version,
  54. you should always build your GDNative module against headers matching the
  55. Godot stable branch (e.g. ``3.1``) and ideally actual release (e.g.
  56. ``3.1.1-stable``) that you use.
  57. GDNative modules built against older versions of the Godot headers *may*
  58. work with newer versions of the engine, but not the other way around.
  59. The ``master`` branch of the ``godot-headers`` repository is kept in line with
  60. the ``master`` branch of Godot and thus contains the GDNative class and
  61. structure definitions that will work with the latest development builds.
  62. If you want to write a GDNative module for a stable version of Godot, look at
  63. the available Git tags (with ``git tags``) for the one matching your engine
  64. version. In the ``godot-headers`` repository, such tags are prefixed with
  65. ``godot-``, so you can e.g. checkout the ``godot-3.1.1-stable`` tag for use with
  66. Godot 3.1.1. In your cloned repository, you can do:
  67. .. code-block:: none
  68. git checkout godot-3.1.1-stable
  69. If a tag matching your stable release is missing for any reason, you can fall
  70. back to the matching stable branch (e.g. ``3.1``), which you would also check
  71. out with ``git checkout 3.1``.
  72. If you are building Godot from source with your own changes that impact
  73. GDNative, you can find the updated class and structure definition in
  74. ``<godotsource>/modules/gdnative/include``
  75. Our C source
  76. ------------
  77. Let's start by writing our main code. Eventually, we want to end up with a file
  78. structure that looks along those lines:
  79. .. code-block:: none
  80. + <your development folder>
  81. + godot-headers
  82. - <lots of files here>
  83. + simple
  84. + bin
  85. - libsimple.dll/so/dylib
  86. - libsimple.gdnlib
  87. - simple.gdns
  88. main.tscn
  89. project.godot
  90. + src
  91. - simple.c
  92. Open up Godot and create a new project called "simple" alongside your
  93. ``godot-headers`` Git clone. This will create the ``simple`` folder and
  94. ``project.godot`` file. Then manually create a ``src`` folder alongside the
  95. ``simple`` folder, and a ``bin`` subfolder in the ``simple`` folder.
  96. We're going to start by having a look at what our ``simple.c`` file contains.
  97. Now, for our example here we're making a single C source file without a header
  98. to keep things simple. Once you start writing bigger projects it is advisable
  99. to break your project up into multiple files. That however falls outside of the
  100. scope of this tutorial.
  101. We'll be looking at the source code bit by bit so all the parts below should all
  102. be put together into one big file. Each section will be explained as we add it.
  103. .. code-block:: C
  104. #include <gdnative_api_struct.gen.h>
  105. #include <string.h>
  106. const godot_gdnative_core_api_struct *api = NULL;
  107. const godot_gdnative_ext_nativescript_api_struct *nativescript_api = NULL;
  108. The above code includes the GDNative API struct header and a standard header
  109. that we will use further down for string operations.
  110. It then defines two pointers to two different structs. GDNative supports a large
  111. collection of functions for calling back into the main Godot executable. In
  112. order for your module to have access to these functions, GDNative provides your
  113. application with a struct containing pointers to all these functions.
  114. To keep this implementation modular and easily extendable, the core functions
  115. are available directly through the "core" API struct, but additional functions
  116. have their own "GDNative structs" that are accessible through extensions.
  117. In our example, we access one of these extension to gain access to the functions
  118. specifically needed for NativeScript.
  119. A NativeScript behaves like any other script in Godot. Because the NativeScript
  120. API is rather low level, it requires the library to specify many things more
  121. verbosely than other scripting systems, such as GDScript. When a NativeScript
  122. instance gets created, a library-given constructor gets called. When that
  123. instance gets destroyed, the given destructor will be executed.
  124. .. code-block:: C
  125. void *simple_constructor(godot_object *p_instance, void *p_method_data);
  126. void simple_destructor(godot_object *p_instance, void *p_method_data, void *p_user_data);
  127. godot_variant simple_get_data(godot_object *p_instance, void *p_method_data,
  128. void *p_user_data, int p_num_args, godot_variant **p_args);
  129. These are forward declarations for the functions we'll be implementing for our
  130. object. A constructor and destructor is needed. Additionally, the object will
  131. have a single method called ``get_data``.
  132. Next up is the first of the entry points Godot will call when our dynamic
  133. library is loaded. These methods are all prefixed with ``godot_`` (you can
  134. change this later on) followed by their name. ``gdnative_init`` is a function
  135. that initializes our dynamic library. Godot will give it a pointer to a
  136. structure that contains various bits of information we may find useful among
  137. which the pointers to our API structures.
  138. For any additional API structures we need to loop through our extensions array
  139. and check the type of extension.
  140. .. code-block:: C
  141. void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *p_options) {
  142. api = p_options->api_struct;
  143. // Now find our extensions.
  144. for (int i = 0; i < api->num_extensions; i++) {
  145. switch (api->extensions[i]->type) {
  146. case GDNATIVE_EXT_NATIVESCRIPT: {
  147. nativescript_api = (godot_gdnative_ext_nativescript_api_struct *)api->extensions[i];
  148. }; break;
  149. default: break;
  150. }
  151. }
  152. }
  153. Next up is ``gdnative_terminate`` which is called before the library is
  154. unloaded. Godot will unload the library when no object uses it anymore. Here,
  155. you can do any cleanup you may need to do. For our example, we're simply going
  156. to clear our API pointers.
  157. .. code-block:: C
  158. void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *p_options) {
  159. api = NULL;
  160. nativescript_api = NULL;
  161. }
  162. Finally, we have ``nativescript_init`` which is the most important function we'll
  163. need today. This function will be called by Godot as part of loading a GDNative
  164. library and communicates back to the engine what objects we make available.
  165. .. code-block:: C
  166. void GDN_EXPORT godot_nativescript_init(void *p_handle) {
  167. godot_instance_create_func create = { NULL, NULL, NULL };
  168. create.create_func = &simple_constructor;
  169. godot_instance_destroy_func destroy = { NULL, NULL, NULL };
  170. destroy.destroy_func = &simple_destructor;
  171. nativescript_api->godot_nativescript_register_class(p_handle, "SIMPLE", "Reference",
  172. create, destroy);
  173. godot_instance_method get_data = { NULL, NULL, NULL };
  174. get_data.method = &simple_get_data;
  175. godot_method_attributes attributes = { GODOT_METHOD_RPC_MODE_DISABLED };
  176. nativescript_api->godot_nativescript_register_method(p_handle, "SIMPLE", "get_data",
  177. attributes, get_data);
  178. }
  179. We first tell the engine which classes are implemented by calling
  180. ``nativescript_register_class``. The first parameter here is the handle pointer
  181. given to us. The second is the name of our object class. The third is the type
  182. of object in Godot that we 'inherit' from; this is not true inheritance but it's
  183. close enough. Finally, our fourth and fifth parameters are descriptions for our
  184. constructor and destructor.
  185. We then tell Godot about our methods (well our one method in this case), by
  186. calling ``nativescript_register_method`` for each method of our class. In our
  187. case, that is just ``get_data``. Our first parameter is yet again our handle
  188. pointer. The second is again the name of the object class we're registering. The
  189. third is the name of our function as it will be known to GDScript. The fourth is
  190. our attributes setting (see ``godot_method_rpc_mode`` enum in
  191. ``godot-headers/nativescript/godot_nativescript.h`` for possible values). The
  192. fifth and final parameter is a description of which function to call when the
  193. method gets called.
  194. The description struct ``instance_method`` contains the function pointer to the
  195. function itself as first field. The other two fields in these structs are for
  196. specifying per-method userdata. The second is the ``method_data`` field which is
  197. passed on every function call as the ``p_method_data`` argument. This is useful
  198. to reuse one function for different methods on possibly multiple different
  199. script-classes. If the ``method_data`` value is a pointer to memory that needs
  200. to be freed, the third ``free_func`` field can contain a pointer to a function
  201. that will free that memory. That free function gets called when the script
  202. itself (not instance!) gets unloaded (so usually at library-unload time).
  203. Now, it's time to start working on the functions of our object. First, we define
  204. a structure that we use to store the member data of an instance of our GDNative
  205. class.
  206. .. code-block:: C
  207. typedef struct user_data_struct {
  208. char data[256];
  209. } user_data_struct;
  210. And then, we define our constructor. All we do in our constructor is allocate
  211. memory for our structure and fill it with some data. Note that we use Godot's
  212. memory functions so the memory gets tracked and then return the pointer to our
  213. new structure. This pointer will act as our instance identifier in case multiple
  214. objects are instantiated.
  215. This pointer will be passed to any of our functions related to our object as a
  216. parameter called ``p_user_data``, and can both be used to identify our instance
  217. and to access its member data.
  218. .. code-block:: C
  219. void *simple_constructor(godot_object *p_instance, void *p_method_data) {
  220. user_data_struct *user_data = api->godot_alloc(sizeof(user_data_struct));
  221. strcpy(user_data->data, "World from GDNative!");
  222. return user_data;
  223. }
  224. Our destructor is called when Godot is done with our object and we free our
  225. instances' member data.
  226. .. code-block:: C
  227. void simple_destructor(godot_object *p_instance, void *p_method_data, void *p_user_data) {
  228. api->godot_free(p_user_data);
  229. }
  230. And finally, we implement our ``get_data`` function. Data is always sent and
  231. returned as variants so in order to return our data, which is a string, we first
  232. need to convert our C string to a Godot string object, and then copy that string
  233. object into the variant we are returning.
  234. .. code-block:: C
  235. godot_variant simple_get_data(godot_object *p_instance, void *p_method_data,
  236. void *p_user_data, int p_num_args, godot_variant **p_args) {
  237. godot_string data;
  238. godot_variant ret;
  239. user_data_struct *user_data = (user_data_struct *)p_user_data;
  240. api->godot_string_new(&data);
  241. api->godot_string_parse_utf8(&data, user_data->data);
  242. api->godot_variant_new_string(&ret, &data);
  243. api->godot_string_destroy(&data);
  244. return ret;
  245. }
  246. Strings are heap-allocated in Godot, so they have a destructor which frees the
  247. memory. Destructors are named ``godot_TYPENAME_destroy``. When a Variant gets
  248. created with a String, it references the String. That means that the original
  249. String can be "destroyed" to decrease the ref-count. If that does not happen the
  250. String memory will leak since the ref-count will never be zero and the memory
  251. never deallocated. The returned variant gets automatically destroyed by Godot.
  252. .. note::
  253. In more complex operations it can be confusing the keep track of which value
  254. needs to be deallocated and which does not. As a general rule: call
  255. ``godot_TYPENAME_destroy`` when a C++ destructor would be called instead.
  256. The String destructor would be called in C++ after the Variant was created,
  257. so the same is necessary in C.
  258. The variant we return is destroyed automatically by Godot.
  259. And that is the whole source code of our module.
  260. Compiling
  261. ---------
  262. We now need to compile our source code. As mentioned our example project on
  263. GitHub contains a SCons configuration that does all the hard work for you, but
  264. for our tutorial here we are going to call the compilers directly.
  265. Assuming you are sticking to the folder structure suggested above, it is best to
  266. open a terminal session in the ``src`` folder and execute the commands from
  267. there. Make sure to create the ``bin`` folder before you proceed.
  268. On Linux:
  269. .. code-block:: none
  270. gcc -std=c11 -fPIC -c -I../godot-headers simple.c -o simple.o
  271. gcc -rdynamic -shared simple.o -o ../simple/bin/libsimple.so
  272. On macOS:
  273. .. code-block:: none
  274. clang -std=c11 -fPIC -c -I../godot-headers simple.c -o simple.os
  275. clang -dynamiclib simple.os -o ../simple/bin/libsimple.dylib
  276. On Windows:
  277. .. code-block:: none
  278. cl /Fosimple.obj /c simple.c /nologo -EHsc -DNDEBUG /MD /I. /I..\godot-headers
  279. link /nologo /dll /out:..\simple\bin\libsimple.dll /implib:..\simple\bin\libsimple.lib simple.obj
  280. .. note::
  281. On the Windows build you also end up with a ``libsimple.lib`` library. This
  282. is a library that you can compile into a project to provide access to the
  283. DLL. We get it as a byproduct and we do not need it :)
  284. When exporting your game for release this file will be ignored.
  285. Creating the GDNativeLibrary (``.gdnlib``) file
  286. -----------------------------------------------
  287. With our module compiled, we now need to create a corresponding
  288. :ref:`GDNativeLibrary <class_GDNativeLibrary>` resource with ``.gdnlib``
  289. extension which we place alongside our dynamic libraries. This file tells Godot
  290. what dynamic libraries are part of our module and need to be loaded per
  291. platform.
  292. We can use Godot to generate this file, so open the "simple" project in the
  293. editor.
  294. Start by clicking the create resource button in the Inspector:
  295. .. image:: img/new_resource.gif
  296. And select ``GDNativeLibrary``:
  297. .. image:: img/gdnativelibrary_resource.png
  298. You should see a contextual editor appear in the bottom panel. Use the "Expand
  299. Bottom Panel" button in the bottom right to expand it to full height:
  300. .. image:: img/gdnativelibrary_editor.png
  301. General properties
  302. ~~~~~~~~~~~~~~~~~~
  303. In the Inspector, you have various properties to control loading the library.
  304. If *Load Once* is enabled, our library is loaded only once and each individual
  305. script that uses our library will use the same data. Any variable you define
  306. globally will be accessible from any instance of your object you create. If
  307. *Load Once* is disabled, a new copy of the library is loaded into memory each
  308. time a script accesses the library.
  309. If *Singleton* is enabled, our library is automatically loaded and a function
  310. called ``godot_gdnative_singleton`` is called. We'll leave that for another
  311. tutorial.
  312. The *Symbol Prefix* is a prefix for our core functions, such as ``godot_`` in
  313. ``godot_nativescript_init`` seen earlier. If you use multiple GDNative libraries
  314. that you wish to statically link, you will have to use different prefixes. This
  315. again is a subject to dive into deeper in a separate tutorial, it is only needed
  316. at this time for deployment to iOS as this platform does not like dynamic
  317. libraries.
  318. *Reloadable* defines whether the library should be reloaded when the editor
  319. loses and gains focus, typically to pick up new or modified symbols from any
  320. change made to the library externally.
  321. Platform libraries
  322. ~~~~~~~~~~~~~~~~~~
  323. The GDNativeLibrary editor plugin lets you configure two things for each
  324. platform and architecture that you aim to support.
  325. The *Dynamic Library* column (``entry`` section in the saved file) tells us for
  326. each platform and feature combination which dynamic library has to be loaded.
  327. This also informs the exporter which files need to be exported when exporting to
  328. a specific platform.
  329. The *Dependencies* column (also ``dependencies`` section) tells Godot what other
  330. files need to be exported for each platform in order for our library to work.
  331. Say that your GDNative module uses another DLL to implement functionality from a
  332. 3rd party library, this is where you list that DLL.
  333. For our example, we only built libraries for Linux, macOS and/or Windows, so you
  334. can link them in the relevant fields by clicking the folder button. If you built
  335. all three libraries, you should have something like this:
  336. .. image:: img/gdnativelibrary_editor_complete.png
  337. Saving the resource
  338. ~~~~~~~~~~~~~~~~~~~
  339. We can then save our GDNativeLibrary resource as ``bin/libsimple.gdnlib`` with
  340. the Save button in the Inspector:
  341. .. image:: img/gdnativelibrary_save.png
  342. The file is saved in a text-based format and should have contents similar to
  343. this:
  344. .. code-block:: none
  345. [general]
  346. singleton=false
  347. load_once=true
  348. symbol_prefix="godot_"
  349. reloadable=true
  350. [entry]
  351. OSX.64="res://bin/libsimple.dylib"
  352. OSX.32="res://bin/libsimple.dylib"
  353. Windows.64="res://bin/libsimple.dll"
  354. X11.64="res://bin/libsimple.so"
  355. [dependencies]
  356. OSX.64=[ ]
  357. OSX.32=[ ]
  358. Windows.64=[ ]
  359. X11.64=[ ]
  360. Creating the NativeScript (``.gdns``) file
  361. ------------------------------------------
  362. With our ``.gdnlib`` file we've told Godot how to load our library, now we need
  363. to tell it about our "SIMPLE" object class. We do this by creating a
  364. :ref:`NativeScript <class_NativeScript>` resource file with ``.gdns`` extension.
  365. Like done for the GDNativeLibrary resource, click the button to create a new
  366. resource in the Inspector and select ``NativeScript``:
  367. .. image:: img/nativescript_resource.png
  368. The inspector will show a few properties that we need to fill. As *Class Name*
  369. we enter "SIMPLE" which is the object class name that we declared in our C
  370. source when calling ``godot_nativescript_register_class``. We also need to
  371. select our ``.gdnlib`` file by clicking on *Library* and selecting *Load*:
  372. .. image:: img/nativescript_library.png
  373. .. note::
  374. The *Class Name* must have the same spelling as the one given in ``godot_nativescript_init``
  375. when registering the class.
  376. Finally, click on the save icon and save this as ``bin/simple.gdns``:
  377. .. image:: img/save_gdns.gif
  378. Now it's time to build our scene. Add a Control node to your scene as your root
  379. and call it ``main``. Then add a Button and a Label as child nodes. Place them
  380. somewhere nice on screen and give your button a name.
  381. .. image:: img/c_main_scene_layout.png
  382. Select the control node and attach a script to it:
  383. .. image:: img/add_main_script.gif
  384. Next link up the ``pressed`` signal on the button to your script:
  385. .. image:: img/connect_button_signal.gif
  386. Don't forget to save your scene, call it ``main.tscn``.
  387. Now we can implement our ``main.gd`` code:
  388. ::
  389. extends Control
  390. # load the Simple library
  391. onready var data = preload("res://bin/simple.gdns").new()
  392. func _on_Button_pressed():
  393. $Label.text = "Data = " + data.get_data()
  394. After all that, our project should work. The first time you run it Godot will
  395. ask you what your main scene is and you select your ``main.tscn`` file and
  396. presto:
  397. .. image:: img/c_sample_result.png