【问题标题】:How to use C# static string with Nlua如何在 Nlua 中使用 C# 静态字符串
【发布时间】:2014-03-27 10:42:04
【问题描述】:

我正在使用 NLua 作为我的应用程序的脚本接口。 我想将键盘输入从 LUA 语言发送到我的 C# 代码。

我使用这个 C# 代码。

   using (Lua lua = new Lua())
   {
      lua.LoadCLRPackage();

      lua.RegisterFunction("keypressC", null, typeof(TestNLUA).GetMethod("keypressC"));
      lua.RegisterFunction("keypressS", null, typeof(TestNLUA).GetMethod("keypressS"));

      lua["Key"] = new SpecialKey();
   }

    public class SpecialKey
    {
        public static readonly char EnterC = '\uE007'; 
        public static readonly string EnterS = Convert.ToString(EnterC);
    }

   public class TestNLUA
   {
      public static void keypressC(char key)
      {
         // key = 57351 => OK
      }

      public static void keypressS(string key)
      {
         char[] akey = key.ToCharArray();
         // akey[0] = 63 = ? (question mark) => KO
      }
   }

在 LUA 脚本中我会这样做

keypressC(Key.EnterC)
keypressS(Key.EnterS)

在 keypressC 中,Nlua 将值 57351 传递给 key 参数。没关系。

在 keypressS 中,Nlua 传递值“?”到关键参数。是KO​​。 我不知道为什么会有字符“?”。 看起来像是 NLua 中的编组错误(即 LuaInterface)?

你能帮帮我吗?

【问题讨论】:

    标签: c# lua nlua


    【解决方案1】:

    这是 nLua/LuaInterface 中的编组问题。

    它使用Marshal.StringToHGlobalAnsi 将字符串从 C# 编组到 Lua。
    它使用Marshal.PtrToStringAnsi 将字符串从 Lua 编组到 C#。

    如果您通过这些函数往返您的示例字符串,您可以看到它重现了您的问题:

     string test = "\uE007";
    
     Console.WriteLine(test);
     Console.WriteLine("{0}: {1}", test[0], (int) test[0]);
    
     IntPtr ptr = Marshal.StringToHGlobalAnsi(test);
     string roundTripped = Marshal.PtrToStringAnsi(ptr, test.Length);
    
     Console.WriteLine(roundTripped);
     Console.WriteLine("{0}: {1}", roundTripped[0], (int) roundTripped[0]);
    

    输出:

    ?
    ?: 57351
    ?
    ?: 63
    

    如果您将编组函数更改为使用 Uni 而不是 Ansi,您的问题就会消失,但您需要从源代码构建 nLua/LuaInterface。

    【讨论】:

    • 由于 nLua/LuaInterface 中的编组问题,我测试了 NeoLua,Lua for .net 动态语言运行时。实际上 NeoLua 使用 .NET 字符串,您可以使用所有功能,例如' test ':Trim()
    • 我试过 NeoLua,但它的 bug 太大了。例如,即使是 "simple example" on their documentation page 也会崩溃。
    • 我没有问题。在codeplex 上打开讨论,NeoLithos 快速响应。
    • 已在 NLua 中修复,即将在 NuGet 中 github.com/NLua/NLua/commit/…
    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2011-01-06
    相关资源
    最近更新 更多