In Chakra Core, how do you returns values without causing memory issues?

319 Views Asked by At

I've been following this example here in an attempt to create a simple javascript engine that can execute javascript like the zxcvbn library. I thought I had it figured out but there are some parts of the sample I don't understand. Specifically, how to get values out of a javascript function without causing any memory issue.

https://github.com/Microsoft/Chakra-Samples/tree/master/ChakraCore%20Samples/JSRT%20Hosting%20Samples/C%23

Here is the example I've created. https://github.com/janmchan/ChakraCoreHostC-

It runs fine but when I use it in a real project, I often get crashes similar to the issue described below (Access violation exception).

https://github.com/Microsoft/Chakra-Samples/issues/4

Here is the solution for that issue. However, I don't quite understand that part of the sample. If you run the sample, it just returns a double of what ever the script returned. I don't even get how the runScriptDelegate is called back.

Thanks for asking, and yes of course.

On a high level, most of the AV issues here come from that in the C# app, installed callbacks are not retained and got garbage collected before being invoked. For example, you create a function like this,

//JsNativeFunction callback
private static JavaScriptValue nativeFunction(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData) 
{
    //do something here
}

...

JsCreateFunction(nativeFunction, callbackData, func);
1

There are 1 best solutions below

0
On

I think I've resolved the issue by looking at JavaScriptEngineSwitcher. From what I understand they have a ScriptDispatcher that handles the threading. I also added some similar code for adding and removing references to the parameters. I'll get back here to confirm if this does resolve the issue in the long term.

https://raw.githubusercontent.com/Taritsyn/JavaScriptEngineSwitcher/2.X/src/JavaScriptEngineSwitcher.ChakraCore/ChakraCoreJsEngine.cs

Update 2018-03-06: This indeed resolved our issue. Here is the sample of the changes I needed to make.

Repository: https://github.com/janmchan/ChakraCoreHostC-

Commit: https://github.com/janmchan/ChakraCoreHostC-/commit/da5810f8f559ebe8ce2c2e50cd8808dc91caa087