I had been trying to load the library dynamically by creating an new ApplicationDomain and passing that to the loader context for the load. What I was doing wrong was storing a reference to that ApplicationDomain and trying to get the definition from that reference. For some reason that was returning null. By implementing paleozogt's answer and altering that to load the swf dynamically, I ended up with the correct code which doesn't use a stored reference to the ApplicationDomain but gets it from the loader's contentLoaderInfo.
Here's the code if you want to load the library dynamically:
package
{
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class AlchemyDynamicLoad
{
private var _library:Object;
private var _loader:Loader;
public function AlchemyDynamicLoad()
{
var loaderContext:LoaderContext = new LoaderContext(false, new ApplicationDomain());
var request:URLRequest = new URLRequest("../assets/mylib.swf");
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
_loader.load(request, loaderContext);
}
private function completeHandler(event:Event):void
{
// NOTE: Storing a reference to the application domain you feed to the loaderContext and then trying to get the
// definition from that reference is not going to work for some reason. You have to get the applicationDomain
// from the contentLoaderInfo, otherwise getDefinition returns null.
var libClass:Class = Class(_loader.contentLoaderInfo.applicationDomain.getDefinition("cmodule.mylib.CLibInit"));
_library = new libClass().init();
}
}
}
And here's the code if you want to embed it (paleozogt's answer):
package
{
import flash.display.Loader;
import flash.events.Event;
public class AlchemyStaticLoad
{
[Embed(source="../assets/mylib.swf", mimeType="application/octet-stream")]
private static var _libraryClass:Class;
private var _library:Object;
private var _loader:Loader;
public function AlchemyStaticLoad()
{
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
_loader.loadBytes(new _libraryClass());
}
private function completeHandler(event:Event):void
{
var libClass:Class = Class(_loader.contentLoaderInfo.applicationDomain.getDefinition("cmodule.mylib.CLibInit"));
_library = new libClass().init();
}
}
}