When you make a native extension, you’ll find that the communication between ActionScript and native code is somewhat lopsided.
Native code in reactive mode
ActionScript normally acts kinda bossy and sends commands to native code. For this purpose it uses the call() method of the flash.external.ExtensionContext class. Native code in return mostly speaks when spoken to.
Native code has two options for communicating back at the time of the call:
- responding to call() by returning a result, wrapped as a FREObject;
- responding to call() by modifying one or more of the parameters passed to it.
Native code in proactive mode
What happens when native code has something it needs to get off its chest and it’s not being addressed? I.e. it’s not inside a call().
This could be: letting ActionScript know that an error condition has appeared (“shit hit fan” message) or that an asynchronous operation has completed (“your results are ready, sir” message).
Well, then native code knocks on ActionScript’s office door, clears its throat and blurts out:
FREResult FREDispatchStatusEventAsync(FREContext context, const uint8_t* code, const uint8_t* level);
This is the C-version of the function that native code can call to send an asynchronous event to ActionScript. The Java equivalent is a method of the Java class FREContext:
public void dispatchStatusEventAsync( String code, String level )
In either language the protocol is that native code provides three pieces of information:
- context – the extension context, which must have been previously created by ActionScript and passed on to native code;
- code – the message code as a string of characters, for example “MESSAGE_SHIT_HIT_FAN”;
- level – another string of characters, describing the message level, for example “REALLY BADLY”.
ActionScript receives this information in the form of an event, namely flash.events.StatusEvent, for which it will need to have a handler.
Example of native code (Objective-C) sending a message to ActionScript:FREDispatchStatusEventAsync(ctx, (uint8_t *) [@"SHIT_HIT_FAN" UTF8String],(uint8_t *) [@"Byte copying failed" UTF8String]);
Example ActionScript code for handling the message:
private function onStatusEvent( _event : StatusEvent ) : void
switch ( _event.code )
displayAlert( _event.level );
- See how to send events from C or Objective-C to ActionScript.
- See how to send events from Java to ActionScript.
Over to you
Right after we published this post our editor spotted a little blunder in one of the pictures (*). Can you see it?
Give it a shot in the comments below.
(*) Editor’s note: So, you’re probably asking: why didn’t you fix the blunder, DiaDraw team?
Well, the answer is complicated and the polite version is that the author was in love with the cartoons and wouldn’t let anyone touch them. The more realistic version involves a lot of shouting and the office cat disappearing for three days… Can’t get the staff these days.