Chapter 10. Interfacing with the Target Platform
Working with your platform.
Being able to use the interns of the platform you are targeting or to work with native code can be really useful: it may lead to being able to easily use some functionality of a library or to optimize your code. However, it also has its drawbacks.
We have now learned about the basics of haXe and are going to get into more technical stuff—interfacing with the target platform. Doing so may be really useful for several things, such as using a library that has been written for the target platform. It is sometimes useful in order to optimize your code too.
In this chapter we will:
So, if you are ready, let's go on!
Extern classes allow one to tell the compiler what classes exist outside of your own code. This way, the compiler won't tell you that the class does not exist and it will also know what fields exist in it and what their type is.
Time for action – Writing an extern
Imagine that we are writing a User
class in JavaScript:
Now, if we want to use this class from our haXe application, then we have to write the corresponding extern
class as follows:
There are several things that you should note:
You have to prefix your class declaration with the extern
keyword
We do not write any code inside function declaration
Constructors should be declared returning Void
We have written an extern class, explaining to the compiler that the User
class exists outside our code and can be used from it.
Now, we can use this class in our haXe code:
Native types and haXe types
haXe defines some types that may already exist in the target platform.
For example, haXe defines the Array
class. The Array
class is already defined on almost all target platforms. The thing is that on some targets, the haXe array and the native array may indeed be different.
In such cases, when working with externs, you may need to convert from a haXe array to a native array and vice-versa.
You have to pay particular attention to that when working with Neko and PHP.
If you are targeting Neko or PHP, then you will have to pay particular attention to array and string. Indeed, in the Neko and PHP packages, you will find the native array and native string types.
There are also 'functions and methods that you can use to convert a native type to the haXe one.
The following are the functions that you can use in PHP to convert from native types to haXe types: