Created
January 14, 2016 12:22
-
-
Save mayuki/fe5f6340f22b2f14b699 to your computer and use it in GitHub Desktop.
ChakraCore Sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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