loading...

C/Hashlink Pointers

amir_rezai profile image Amir Mohammad Rezai ・2 min read

Lately I started rewriting SDL bindings for hashlink, since SDL bindings are already written for hashlink here, but I really wanted to see how it works by both checking original code written and rewriting most of the functions that has not been ported.

This rewrite is not yet complete but I learnt so many things like how to interact with C pointers in hashlink and it's super easy, yet there is no documentation available for Hashlink/C API.

Take this simple C function as an export example:

HL_PRIM void HL_NAME(destroy_window)(SDL_Window * win) {
  SDL_DestroyWindow(win);
}

destroy_window is actually a name for a function exported to haxe. I use an external class and call it NativeSDLWindow.

@:hlNative("sdl2")
extern class NativeSDLWindow {
   public static function destroy_window(window:NativeSDLWindowPointer):Void;
}

Defining pointers are easy. in three simple steps:
1) define an abstract with name in C header file or anywhere in you C source.

#define _SDL_WINDOW _ABSTRACT(sdl_window)

2) define a type in haxe files, I usually use Native(X)Pointer to keep consistency in this case:

#if hl
typedef NativeSDLWindowPointer = hl.Abstract<"sdl_window">;
#end

keep in mind i used same name as _ABSTRACT(X) defined in C.
3) Define prim in with your source code (recently I found that these exports are not working as intended at least in C native compilation but might be needed for hashlink virtual machine to work with them.)

DEFINE_PRIM(_VOID, destroy_window, _SDL_WINDOW)

And that's all, you can use this way to port most of C functions to hashlink.
If you don't know how to compile hdll refer to my previous article about hashlink prims.

Thank you for your time.

Posted on by:

amir_rezai profile

Amir Mohammad Rezai

@amir_rezai

I'm a game developer, with performance issues in mind. Live in Nerverland, Iran.

Discussion

markdown guide