gdnative-c-example.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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'll be
  11. describing here by following this link:
  12. https://github.com/GodotNativeTools/GDNative-demos/tree/master/c/SimpleDemo
  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.
  15. :ref:`GDNative <class_GDNative>` can be used to create several types of
  16. additions to Godot, from PluginScript to ARVR interfaces. In this tutorial we
  17. are going to look at creating a :ref:`NativeScript <class_NativeScript>` module.
  18. NativeScript allows you to write logic in C or C++ in similar fashion as you
  19. would write a GDScript file. We'll be creating the C equivalent of this
  20. GDScript:
  21. ::
  22. extends Reference
  23. var data
  24. func _ready():
  25. data = "World from GDScript!"
  26. func get_data():
  27. return data
  28. We'll be writing separate tutorials on the other types of GDNative modules and
  29. explain what each of them is for as we go through them.
  30. Prerequisites
  31. -------------
  32. Before we start you'll need a few things.
  33. 1) A Godot 3.0 executable
  34. 2) A C compiler
  35. 3) A copy of this repository: https://github.com/GodotNativeTools/godot_headers
  36. The first two pretty much speak for themselves. On Linux, you'll likely have a C
  37. compiler, on macOS, it's easiest to install Xcode from the Mac App Store and, on
  38. Windows, we've tested this with both MSVC 2015 and 2017.
  39. For number 3, we suggest that you create a folder somewhere that you use to
  40. store your code, open up a terminal and CD into that folder. Then execute:
  41. .. code-block:: none
  42. git clone https://github.com/GodotNativeTools/godot_headers
  43. This will download the required files into that folder.
  44. .. note::
  45. On this repository you will now find different branches. As Godot evolves, so
  46. does GDNative. With the exception of one breaking change in ARVR between 3.0
  47. and 3.1, GDNative modules build for older versions of Godot will work with
  48. newer versions of Godot but not the other way around.
  49. The master branch of the ``godot_headers`` repository is kept in line with the
  50. master branch of Godot and thus contains the GDNative class and structure
  51. definitions that will work with the latest Godot master.
  52. The 3.0 branch of the ``godot_headers`` repository contains the GDNative class
  53. and structure definitions that will work with Godot 3.0. You can clone this
  54. branch by executing:
  55. .. code-block:: none
  56. git clone https://github.com/GodotNativeTools/godot_headers -b 3.0
  57. If you are building Godot from source with your own changes that impact
  58. GDNative, you can find the updated class and structure definition in
  59. ``<godotsource>/modules/gdnative/include``
  60. Our C source
  61. ------------
  62. Let's start by writing our main code. Ideally, we want to end up with a file
  63. structure that looks something like this:
  64. .. code-block:: none
  65. + <your development folder>
  66. + godot_headers
  67. - <lots of files here>
  68. + simple
  69. + bin
  70. - libsimple.dll/so/dylib
  71. - libsimple.gdnlib
  72. - simple.gdns
  73. + src
  74. - .gdignore
  75. - simple.c
  76. main.tscn
  77. project.godot
  78. Open up Godot and create a new project called simple. This will create the
  79. ``simple`` folder and ``project.godot`` file. Then manually create a ``bin`` and
  80. ``src`` subfolder in this folder.
  81. We're going to start by having a look at what our ``simple.c`` file contains.
  82. Now, for our example here we're making a single C source file without a header
  83. to keep things simple. Once you start writing bigger projects it is advisable
  84. you break your project up into multiple files. That however falls outside of the
  85. scope of this tutorial.
  86. We'll be looking at the source code bit by bit so all the parts below should all
  87. be put together into one big file. I'll explain each section as we add it.
  88. The below code includes our header files that we need and then defines two
  89. pointers to two different structs. GDNative supports a large collection for
  90. functions for calling back into the main Godot executable. In order for your
  91. module to have access to these functions, GDNative provides your application
  92. with a struct containing pointers to all these functions.
  93. To keep this implementation modular and easily extendable, the core functions
  94. are available directly through the "core" API struct, but additional functions
  95. have their own "GDNative structs" that are accessible through extensions.
  96. In our example, we access one of these extension to gain access to the functions
  97. specifically needed for NativeScript.
  98. .. code-block:: C
  99. #include <gdnative_api_struct.gen.h>
  100. #include <stdio.h>
  101. #include <stdlib.h>
  102. #include <string.h>
  103. const godot_gdnative_core_api_struct *api = NULL;
  104. const godot_gdnative_ext_nativescript_api_struct *nativescript_api = NULL;
  105. A NativeScript behaves like any other script in Godot. Because the NativeScript
  106. API is rather low level, it requires the library to specify many things more
  107. verbosely than other scripting systems, such as GDScript. When a NativeScript
  108. instance gets created, a library-given constructor gets called. When that
  109. instance gets destroyed, the given destructor will be executed.
  110. These are forward declarations for the functions we'll be implementing for our
  111. object. A constructor and destructor is needed. Additionally, the object will
  112. have a single method called get_data.
  113. .. code-block:: C
  114. void *simple_constructor(godot_object *p_instance, void *p_method_data);
  115. void simple_destructor(godot_object *p_instance, void *p_method_data, void *p_user_data);
  116. godot_variant simple_get_data(godot_object *p_instance, void *p_method_data
  117. , void *p_user_data, int p_num_args, godot_variant **p_args);
  118. Next up is the first of the entry points Godot will call when our dynamic
  119. library is loaded. These methods are all prefixed with Godot (you can change
  120. this later on) followed by their name. ``gdnative_init`` is a function that
  121. initialises our dynamic library. Godot will give it a pointer to a structure
  122. that contains various bits of information we may find useful amongst which the
  123. pointers to our API structures.
  124. For any additional API structures we need to loop through our extensions array
  125. and check the type of extension.
  126. .. code-block:: C
  127. void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *p_options) {
  128. api = p_options->api_struct;
  129. // now find our extensions
  130. for (int i = 0; i < api->num_extensions; i++) {
  131. switch (api->extensions[i]->type) {
  132. case GDNATIVE_EXT_NATIVESCRIPT: {
  133. nativescript_api = (godot_gdnative_ext_nativescript_api_struct *)api->extensions[i];
  134. }; break;
  135. default: break;
  136. }
  137. }
  138. }
  139. Next up is ``gdnative_terminate`` which is called before the library is
  140. unloaded. Godot will unload the library when no object uses it anymore. Here,
  141. you can do any cleanup you may need to do. For our example, we're simply going
  142. to clear our API pointers.
  143. .. code-block:: C
  144. void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *p_options) {
  145. api = NULL;
  146. nativescript_api = NULL;
  147. }
  148. Finally we have ``nativescript_init`` which is the most important function we'll
  149. need today. This function will be called by Godot as part of loading a GDNative
  150. library and communicates back to Godot what objects we make available to Godot.
  151. We first tell Godot which classes are implemented by calling
  152. ``nativescript_register_class``. The first parameter here is the handle pointer
  153. given to us. The second is the name of our object class. The third is the type
  154. of object in Godot that we 'inherit' from, this is not true inheritance but it's
  155. close enough. Finally, our fourth and fifth parameters are descriptions for our
  156. constructor and destructor.
  157. We then tell Godot about our methods (well our one method in this case), by
  158. calling ``nativescript_register_method`` for each method of our class. In our
  159. case, that is just ``get_data``. Our first parameter is yet again our handle
  160. pointer. The second is again the name of the object class we're registering. The
  161. third is the name of our function as it will be known to GDScript. The fourth is
  162. our attributes setting. The fifth and final parameter is a description of which
  163. function to call when the method gets called.
  164. The descriptions contain the function pointers to the functions themselves. The
  165. other two fields in these structs are for specifying per-method userdata. The
  166. value in the ``method_data`` field will be passed on every function call as the
  167. ``p_method_data`` argument. This is useful to reuse one function for different
  168. methods on possibly multiple different script-classes. If the ``method_data``
  169. value is a pointer to memory that needs to be freed, the ``free_func`` field can
  170. contain a pointer to a function that will free that memory. That free function
  171. gets called when the script itself (not instance!) gets unloaded (so usually at
  172. library-unload time).
  173. .. code-block:: C
  174. void GDN_EXPORT godot_nativescript_init(void *p_handle) {
  175. godot_instance_create_func create = { NULL, NULL, NULL };
  176. create.create_func = &simple_constructor;
  177. godot_instance_destroy_func destroy = { NULL, NULL, NULL };
  178. destroy.destroy_func = &simple_destructor;
  179. nativescript_api->godot_nativescript_register_class(p_handle, "SIMPLE", "Reference",
  180. create, destroy);
  181. godot_instance_method get_data = { NULL, NULL, NULL };
  182. get_data.method = &simple_get_data;
  183. godot_method_attributes attributes = { GODOT_METHOD_RPC_MODE_DISABLED };
  184. nativescript_api->godot_nativescript_register_method(p_handle, "SIMPLE", "get_data",
  185. attributes, get_data);
  186. }
  187. Now, it's time to start working on the functions of our object. First, we define
  188. a structure that we use to store the member data of an instance of our GDNative
  189. class.
  190. .. code-block:: C
  191. typedef struct user_data_struct {
  192. char data[256];
  193. } user_data_struct;
  194. And then, we define our constructor. All we do in our constructor is allocate
  195. memory for our structure and fill it with some data. Note that we use Godot's
  196. memory functions so the memory gets tracked and then return the pointer to our
  197. new structure. This pointer will act as our instance identifier in case multiple
  198. objects are instantiated.
  199. This pointer will be passed to any of our functions related to our object as a
  200. parameter called ``p_user_data``, and can both be used to identify our instance
  201. and to access its member data.
  202. .. code-block:: C
  203. void *simple_constructor(godot_object *p_instance, void *p_method_data) {
  204. user_data_struct *user_data = api->godot_alloc(sizeof(user_data_struct));
  205. strcpy(user_data->data, "World from GDNative!");
  206. return user_data;
  207. }
  208. Our destructor is called when Godot is done with our object and we free our
  209. instances' member data.
  210. .. code-block:: C
  211. void simple_destructor(godot_object *p_instance, void *p_method_data, void *p_user_data) {
  212. api->godot_free(p_user_data);
  213. }
  214. And finally, we implement our get_data function. Data is always sent and
  215. returned as variants so in order to return our data, which is a string, we first
  216. need to convert our C string to a Godot string object, and then copy that string
  217. object into the variant we are returning.
  218. Strings are heap-allocated in Godot, so they have a destructor which frees the
  219. memory. Destructors are named ``godot_TYPENAME_destroy``. When a Variant gets
  220. created with a String, it references the String. That means that the original
  221. String can be "destroyed" to decrease the ref-count. If that does not happen the
  222. String memory will leak since the ref-count will never be zero and the memory
  223. never deallocated. The returned variant gets automatically destroyed by Godot.
  224. (In more complex operations it can be confusing the keep track of which value
  225. needs to be deallocated and which does not. As a general rule: call
  226. godot_XXX_destroy when a C++ destructor would be called instead. The String
  227. destructor would be called in C++ after the Variant was created, so the same is
  228. necessary in C)
  229. The variant we return is destroyed automatically by Godot.
  230. .. code-block:: C
  231. godot_variant simple_get_data(godot_object *p_instance, void *p_method_data,
  232. void *p_user_data, int p_num_args, godot_variant **p_args) {
  233. godot_string data;
  234. godot_variant ret;
  235. user_data_struct * user_data = (user_data_struct *) p_user_data;
  236. api->godot_string_new(&data);
  237. api->godot_string_parse_utf8(&data, user_data->data);
  238. api->godot_variant_new_string(&ret, &data);
  239. api->godot_string_destroy(&data);
  240. return ret;
  241. }
  242. And that is the whole source code of our module.
  243. If you add a blank ``.gdignore`` file to the src folder, Godot will not try to
  244. import the compiler-generated temporary files.
  245. Compiling
  246. ---------
  247. We now need to compile our source code. As mentioned our example project on
  248. GitHub contains a Scons configuration that does all the hard work for you but
  249. for our tutorial here we are going to call the compilers directly.
  250. Assuming you are sticking to the folder structure suggested above it is best to
  251. CD into the src subfolder in a terminal session and execute the commands from
  252. there. Make sure to create the bin folder before you proceed.
  253. On Linux:
  254. .. code-block:: none
  255. clang -std=c11 -fPIC -c -I/PATH/TO/GODOT/HEADERS simple.c -o simple.os
  256. clang -shared simple.os -o ../bin/libsimple.so
  257. On macOS:
  258. .. code-block:: none
  259. clang -std=c11 -fPIC -c -I/PATH/TO/GODOT/HEADERS simple.c -o simple.os -arch i386 -arch x86_64
  260. clang -dynamiclib simple.os -o ../bin/libsimple.dylib -arch i386 -arch x86_64
  261. On Windows:
  262. .. code-block:: none
  263. cl /Fosimple.obj /c simple.c /nologo -EHsc -DNDEBUG /MD /I. /IC:\PATH\TO\GODOT\HEADERS
  264. link /nologo /dll /out:..\bin\libsimple.dll /implib:..\bin\libsimple.lib simple.obj
  265. .. note::
  266. on the Windows build you also end up with a libsimple.lib library. This is a
  267. library that you can compile into a project to provide access to the DLL. We
  268. get it as a bonus and we do not need it :) When exporting your game for
  269. release this file will be ignored.
  270. Creating our GDNLIB file
  271. ------------------------
  272. With our module compiled we now need to create a gdnlib file for our module
  273. which we place alongside our dynamic libraries. This file tells Godot what
  274. dynamic libraries are part of our module and need to be loaded per platform. At
  275. the time of writing this tutorial work is still being done on making this
  276. configurable from within Godot so for now grab your favourite text editor,
  277. create a file called libsimple.gdnlib and add the following into this file:
  278. .. code-block:: none
  279. [general]
  280. singleton=false
  281. load_once=true
  282. symbol_prefix="godot_"
  283. [entry]
  284. X11.64="res://bin/libsimple.so"
  285. Windows.64="res://bin/libsimple.dll"
  286. OSX.64="res://bin/libsimple.dylib"
  287. [dependencies]
  288. X11.64=[]
  289. Windows.64=[]
  290. OSX.64=[]
  291. This file contains 3 sections.
  292. The **general** section contains some info that tells Godot how to use our
  293. module.
  294. If singleton is true our library is automatically loaded and a function called
  295. godot_singleton_init is called. We'll leave that for another tutorial.
  296. If load_once is true our library is loaded only once and each individual script
  297. that uses our library will use the same data. Any variable you define globally
  298. will be accessible from any instance of your object you create. If load_once is
  299. false a new copy of the library is loaded into memory each time a script access
  300. the library.
  301. The symbol_prefix is a prefix for our core functions. So the Godot in
  302. godot_nativescript_init for instance. If you use multiple GDnative libraries
  303. that you wish to statically link you'll have to use different prefixes. This
  304. again is a subject to dive into deeper in a separate tutorial, it is only needed
  305. at this time for deployment to iOS as this platform does not like dynamic
  306. libraries.
  307. The **entry** section tells us for each platform and feature combination which
  308. dynamic library has to be loaded. This also informs the exporter which files
  309. need to be exported when exporting to a specific platform.
  310. The **dependencies** section tells Godot what other files need to be exported
  311. for each platform in order for our library to work. Say that your GDNative
  312. module uses another DLL to implement functionality from a 3rd party library,
  313. this is where you list that DLL.
  314. Putting it all together
  315. -----------------------
  316. Now that we should have a working GDNative library it is time to fire up Godot
  317. and use it. Open up the sample project if you haven't left it open after
  318. creating the project all the way at the beginning of this tutorial.
  319. Creating our GDNS file
  320. ----------------------
  321. With our GDNLIB file we've told Godot how to load our library, now we need to
  322. tell it about our "Simple" object class. This we do by creating a GDNS resource
  323. file.
  324. Start by clicking the create resource button in the Inspector:
  325. .. image:: img/new_resource.gif
  326. And select NativeScript:
  327. .. image:: img/nativescript_resource.png
  328. Press Create, now the inspector will show a few fields we need to enter. In
  329. Class Name we enter "SIMPLE" which is the object class name we used in our C
  330. source when calling godot_nativescript_register_class. We also need to select
  331. our GDNLIB file by clicking on Library and selecting Load:
  332. .. image:: img/nativescript_library.png
  333. Finally click on the save icon and save this as bin/simple.gdns:
  334. .. image:: img/save_gdns.gif
  335. Now it's time to build our scene. Add a control node to your scene as your root
  336. and call it main. Then add a button and a label as subnodes. Place them
  337. somewhere nice on screen and give your button a name.
  338. .. image:: img/c_main_scene_layout.png
  339. Select the control node and create a script for the control node:
  340. .. image:: img/add_main_script.gif
  341. Next link up the pressed signal on the button to your script:
  342. .. image:: img/connect_button_signal.gif
  343. Don't forget to save your scene, call it main.tscn.
  344. Now we can implement our main.gd code:
  345. ::
  346. extends Control
  347. # load the SIMPLE library
  348. onready var data = preload("res://bin/simple.gdns").new()
  349. func _on_Button_pressed():
  350. $Label.text = "Data = " + data.get_data()
  351. After all that, our project should work. The first time you run it Godot will
  352. ask you what your main scene is and you select your main.tscn file and presto:
  353. .. image:: img/c_sample_result.png