views:

32

answers:

1

Dear all,

I got a question regarding C++ Object & Javascript Object life cycle mis-synchronization and hope here your gurus could help me out.

Specifically, I am embedding SpiderMonkey in my C++ program. I am not sure if my approach is right or not. What I am doing is like

(1) C++ program loads a Javascript file and call an entry function.

(2) In the entry function, some C++ functions are called to initialize the program. During these calls, some C++ objects will be created.

(3) Based on user interaction, corresponding script function will be called as event handler.

This approach works, but with one problem (there could be unidentified more :)

That is,

In my JS event handler function, I need to fetch a C++ object to the Javascript context and call it member function. For this, in my C++ fetching function, I check if its corresponding JS peer object has been created or not. If not, I use JS_NewObject to create one and return it. Then the JS function could call native function on it.

The problem is that in some cases, the result of such native function call will lead the death of the C++ object. However, I can not find a way to notify the JS context to delete its JS peer object too. I failed to find a JSAPI function to do so.

In my current program, all the JS objects created using JS_NewObject are destroyed when finally the JS runtime is destroyed.

I guess this has something do with SipderMonkey's "garbage collection". But I have not found a good guide yet. Many thanks for any suggestionto

A: 

JS is a GC'd environment so you can't simply "delete" a GC allocated object. There are basically 2 options you can take:

  1. Make your C++ object be dependent on the JS wrapper object, if you were using refcounting for instance you would increment the C++ object's ref when you created a wrapper, and decrement the ref in the wrapper objects finalizer.

  2. When you destroy the C++ object, fetch the wrapper object (if it exists) as clear the reference to the C++ object. All your callbacks will now need to null check prior to using the C++ object, but you won't crash (you could throw a JS exception in response perhaps?)

In most cases option 1 is what users expect.

I'd point to the required API but i don't know the SM API (I know the JSC API instead, but they same concepts apply)

olliej