Pass function as an argument in a function javascript to NPAPI - npapi

On javascript Object i am invoking
obj.requestFileSystem(LOCAL,5*1024*1024) . This method is implemented in PlainNAPI Plugin , now i have to pass one success callback to this function as follows......
obj.requestFileSystem(LOCAL,5*1024*1024,initFS); // initFS is a function in javascript that is an argument to the success callback .
In NPAPI it is an object when the requestFileSystem is completed then initFS function in javascript should be called. How to return from NPAPI plugin to javascript and to execute initFS function.
function initFS(fs) {
alert('Inside the initFS');
alert(fs.root.getFullPath);
}

Please don't tell me what you're actually doing with this plugin, since it sounds like it's something akin to giving people access to things from a web browser that could easily be abused by someone else.
Basically a function is just an NPObject when it gets to your function inside NPRuntime; to call the function you just do a NPN_InvokeDefault on that NPObject.
Note that you must be on the main thread in order to call nearly all NPN_ functions.
EDIT: So if you have to do the callback from a different thread then your easiest solution is to use NPN_PluginThreadAsyncCall; basically you create an object to hold the data you need and call PluginThreadAsyncCall with that pointer as the void* parameter and it will get passed to the function you specify.
Make sure that A) the pointer will still be valid, and B) your function is able to free that memory after it runs. From the callback function you can call NPN_InvokeDefault safely.
Not that NPN_PluginThreadAsyncCall doesn't seem to work on Safari 5.1 anymore. If you need that support or if what I've explained doesn't make sense you might want to consider using FireBreath to build your plugin; it does all of this for you.

Related

Extend Function in Actionscript 3.0

Hi I am creating a Lexer, Parser, and Interpreter for my own simple scripting language in AS3. I'd like this to work similar to JavaScript in that I want to be able to execute instructions at runtime from a parsed script. There is a library for flash that does this but the issue is that VMFunctions are unable to be treated as native flash functions. I'd like to be able to call addEventListener() on native flash objects from the scripting language but I want to pass VM functions to the listener parameter which accepts only native functions. I might have to put in a work around which I know is possible but it would be more intuitive to have an object that the AVM could recognize as a native function maybe using flash_proxy and the Proxy class. So in short, I'd like to create a custom vm function class that extends the native function class in some way or can be treated as such so that when I pass the custom VM function into the addEventListener() method It will not throw a TypeReference kind of error. Thank you.
There's a short answer: Wrap it. You want to call a VMFunction when an event arises? Create an event listener for that event on the control desired, then call the function passing correct data to it. Since this is a parser, it should probably want some text, so here's an example:
var tf:TextField; // your text field, populated elsewhere
var parseButton:Sprite; // click this to parse, bla blabla
function onClick(e:MouseEvent):void {
yourVMFunction(tf.text); // parse output if necessary
}
function Parser() { // constructor
// some code not depicted
parseButton.addEventListener(MouseEvent.CLICK,onClick);
}
The yourVMFunction can be a variable of type Function, should you need to repopulate the code.

NPAPI How can I tell if an NPObject is a function?

In my NPAPI plugin I wish to determine if an NPObject is a function (ie, it is an instance of Function). Any suggestions how I can do this?
I can check with NPN_HasMethod() to see if there is a method called 'call', but I think a better way would be if I could perform the equivalent of javascript's "foo instanceof Function"
I have tried to call NPN_Evaluate, with my 'foo' NPObject as the scope, and a script of "this instanceof Function" but unfortunately the 'this' is the global scope, not my 'foo' object. Am I misunderstanding the intention of the scope parameter here? Any examples I've found are using the window. Being able to use the actual object (or at least the 'this' or a reference to the javascript object) would be preferable (for many other purposes) but any good way to determine if it's a function would be appreciated.
The only way I know of would be to use NPN_Evaluation to inject a function into the global javascript scope and then call it with the NPObject.
For example, inject the following function:
window.isFunction = window.isFunction || function(obj) {
return typeof obj === 'function';
};
Then you can use NPAPI to get the NPObject for the window, get the "isFunction" property, and then do an NPN_InvokeDefault on it with the function you want to check as the parameter.

Do I need to implement the NPN functions myself?

I got my header files from: http://code.google.com/p/npapi-sdk/source/browse/?r=7#svn%2Fwiki
So in the Initialize method, I stored a pointer to all of the browser NPN methods like so
static NPNetscapeFuncs* browser;
NPError NP_Initialize(NPNetscapeFuncs* browserFuncs)
{
/* Save the browser function table. */
browser = browserFuncs;
return NPERR_NO_ERROR;
}
When I am creating my NPClass struct, should I just assign it the already existing browser functions like this:
struct NPClass class;
class.hasMethod = browser-> hasmethod;
etc.
Or do I need to implement the functions in the npruntimeheader using the browser funcs and assign them to the class that way. Example:
class.hasMethod = NPN_HasMethod;
And then implement the function below:
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName)
{
return browser->hasmethod(npp, npobj, methodName);
}
Or are the NPN functions in the runtime header already implemented somehow?
I need to write this in c, and I don't think using firebreath would be a great idea for this particular project. Thanks in advance for your help
You need to implement the functions for your NPClasses yourself, they define the behaviour of your scriptable objects. Part three of taxilians NPAPI tutorial covers this.
The functions that you receive via the browser function table are for calling into the browser (and already implemented there), e.g. to get information about NPObjects with hasmethod etc.
However the function declarations like NPN_HasMethod() need to be implemented by you if you want to use them, at their simplest just calling the corresponding functions in browser as you have shown with HasMethod().

Difference between Callback function and normal function

i have googled a lot to find out the difference between normal function and callback function. Unfortunatley I could not understand. if we have to call a function inside another function, what is usefulness of passing it as a parameter to the function by using function pointers?
Is it possible to call the function passed as a parameter in the form of function pointers somewhere outside the function, in which it is passed as parameter? if yes, please give me a rough idea of its implementation.
Thanks
Say you have a function that does some prolonged operation, like send email. You don't want to wait for it to finish, so you give it a callback function that will invoke once it's done. That's a major use of callbacks - notification of asynchronous operations. There are other uses.

What are callback methods?

I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?
The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).
A trivial example, in Python:
void call_something_three_times(what_to_call, what_to_pass_it):
for i in xrange(3): what_to_call(what_to_pass_it)
# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")
This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.
In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.
Wiki says:
In computer programming, a callback is
a reference to executable code, or a
piece of executable code, that is
passed as an argument to other code.
This allows a lower-level software
layer to call a subroutine (or
function) defined in a higher-level
layer.
In common terms it is the mechanism to notify a piece of code i.e. a method, which piece of code to execute, i.e. another method, when it is needed.
Callback is related to the fact that the client of the calling function specifies a function that belongs to the client code's responsibility to the calling function to execute and this is passed as an argument.
An example is in GUIs. You pass as argument the function to be called once an event occurs (e.g. button pressed) and once the event
occurs this function is called.
This function is usually implemented by the object that originally registered for the event
Callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.
Why Should You Use Callback Functions?
A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the application's queue).
In general you supply a function as a parameter which gets called when something occurs.
In C code you will pass something that looks like this:
int (callback *)(void *, long );
meaning a function that takes two parameters, void * and long and returns an int.
With object-orientated languages the syntax is sometimes simpler. For example you might be able to construct a callback mechanism that allows the user to pass in an object that looks like a function or has an abstract method (thus wrapping a function) and context data too.
Modern languages use the term "delegate" to refer to a function "pattern". These can be used as callbacks. Some languages also use the term lambda which is essentially a function with no name, often created "on the fly" in a block of code and passed as a callback.
C++11 has introduced these into its standard.
The advantage of using a callback is that you can separate out, i.e. reduce / decouple an API from what is calling it, and to some extent vice versa, i.e. although in one place you know you are calling into the API, at the point of the "handler" it does not need to know from where it was called.
For example, you can have an API that generates objects and then "calls-back" as they get generated.
Call back means that you pass the code as a parameter. For example, imagine a button, that much show a dialog when pressed:
Button testBtn;
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onCLick() {
JOptionPane.showDialog(testBtn, "Test button pressed");
}
}
Here we tell the button what to execute, when it will be click. So, the framework will execute the passed code, when it detecs the click. Inside the framework there are some code like:
void processEvent(Event e) {
if (e.type == Event.CLICK) {
e.getComponent().getOnClickListener().onClick();
}
}
So, some basic code calls back the listener when the appropriate event happens.
PS: Pseudocode here, just do describe the idea.
A callback method is a method that gets called when an event occurs
In simple word, actually, a Callback is a reference to a function or method, which you can pass as a parameter to another function for calling it back later.
From the above figure, B_reference() is the callback method.
Source code sample:
>>> def A(A_msg,B_reference):
... # After printing message, method B is called.
... print(A_msg)
... B_reference()
...
>>> def B():
... print("Message from B")
...
>>>
>>> A("Message from A",B)
Message from A
Message from B
>>>
If you still don't understand what it is, you can check this video: