Skip to content

Instantly share code, notes, and snippets.

@mayuki
Created January 14, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayuki/fe5f6340f22b2f14b699 to your computer and use it in GitHub Desktop.
Save mayuki/fe5f6340f22b2f14b699 to your computer and use it in GitHub Desktop.
ChakraCore Sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChakraHost.Hosting;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// ランタイムを作る
JavaScriptRuntime runtime;
Native.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null, out runtime);
// 実行コンテキストを作る
var context = runtime.CreateContext(); // or Native.JsCreateContext(out JavaScriptContext)
// 現在のスレッドの実行コンテキストをセットする
Native.JsSetCurrentContext(context);
// 実行するスクリプト
var script = @"
class Greeter {
hello() { return 'コンニチハ!'; }
}
new Greeter().hello();
";
// スクリプトのソースの位置を記録するためのコンテキスト
var currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
// スクリプトを実行する
JavaScriptValue result;
Native.JsRunScript(script, currentSourceContext++, "", out result);
// 戻り値をJavaScriptの値からCLRのStringに変換する
// ちなみにConvertToStringメソッドはJavaScriptのStringなので注意。
var resultString = result.ToString(); // Native.JsStringToPointer + Marshal.PtrToStringUni
// 出力
Console.WriteLine(resultString);
// 後片付け
Native.JsSetCurrentContext(JavaScriptContext.Invalid);
runtime.Dispose(); // IDisposableなのでusingでもいい
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment