diff --git a/PorygonSharp/CoreSetup.cs b/PorygonSharp/CoreSetup.cs new file mode 100644 index 0000000..db15171 --- /dev/null +++ b/PorygonSharp/CoreSetup.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.InteropServices; + +namespace PorygonSharp +{ + internal static class CoreSetup + { + public static Action Print = Console.WriteLine; + + private delegate void InternalPrintDelegate(IntPtr ptr); + private static InternalPrintDelegate InternalPrint = PrintFunc; + + static CoreSetup() + { + SetPrintFunc(); + } + + internal static void SetPrintFunc() + { + var funcPtr = Marshal.GetFunctionPointerForDelegate(InternalPrint); + InternalSetPrintFunc(funcPtr); + } + + private static void PrintFunc(IntPtr ptr) + { + var message = Marshal.PtrToStringUni(ptr); + Print(message); + } + + [DllImport("libPorygonLang", EntryPoint = "SetPrintFunc", CallingConvention = CallingConvention.Cdecl)] + private static extern double InternalSetPrintFunc(IntPtr ptr); + } +} \ No newline at end of file diff --git a/PorygonSharp/Script.cs b/PorygonSharp/Script.cs index f940fa2..ed2f395 100644 --- a/PorygonSharp/Script.cs +++ b/PorygonSharp/Script.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using PorygonSharp.DiagnosticHandling; @@ -40,8 +41,13 @@ namespace PorygonSharp private Diagnostics _diagnostics; public Diagnostics Diagnostics => _diagnostics ?? (_diagnostics = new Diagnostics(_internalScript.Diagnostics)); + private static readonly RuntimeTypeHandle _setupHandle = typeof(CoreSetup).TypeHandle; + public Script(string s) { + // Ensure core setup has been called + RuntimeHelpers.RunClassConstructor(_setupHandle); + _internalScriptHandle = Create(s); _internalScript = Marshal.PtrToStructure(_internalScriptHandle); } diff --git a/PorygonSharpTests/UnitTest1.cs b/PorygonSharpTests/UnitTest1.cs index ce7a244..eaf080e 100644 --- a/PorygonSharpTests/UnitTest1.cs +++ b/PorygonSharpTests/UnitTest1.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Linq; using NUnit.Framework; using PorygonSharp; @@ -122,11 +123,26 @@ namespace PorygonSharpTests } } + [Test] + public void TestPrint() + { + using (var script = new Script("print('test')")) + { + using (var sw = new StringWriter()) + { + Console.SetOut(sw); + Assert.False(script.Diagnostics.HasErrors()); + script.Evaluate(); + var s = sw.ToString(); + Assert.AreEqual("test\n", s); + } + } + } [Test] public void TestHash() { - var hash = HashedString.ScriptHash("Foo"); + var hash = "Foo".ScriptHash(); Assert.AreEqual(193501609, hash); } } diff --git a/libPorygonLang.so b/libPorygonLang.so index 1d2149a..b155a2b 100755 Binary files a/libPorygonLang.so and b/libPorygonLang.so differ