Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use KeraLua.Lua.NewUserData correctly #71

Closed
maikgreubel opened this issue Jun 11, 2021 · 2 comments
Closed

How to use KeraLua.Lua.NewUserData correctly #71

maikgreubel opened this issue Jun 11, 2021 · 2 comments

Comments

@maikgreubel
Copy link

Hello,

I do not know how to use the function KeraLua.Lua.NewUserData() correctly. I get a valid IntPtr object from it but do not know how to dereference it to a structure. The following code is a stripped-down snippet which causes a System.ExecutionEngineException at:

Fatal error. Internal CLR error. (0x80131506)
   at System.StubHelpers.InterfaceMarshaler.ConvertToManaged(IntPtr, IntPtr, IntPtr, Int32)
   at System.Runtime.InteropServices.Marshal.PtrToStructureHelper(IntPtr, System.Object, Boolean)
   at System.Runtime.InteropServices.Marshal.PtrToStructureHelper(IntPtr, System.Type)
   at System.Runtime.InteropServices.Marshal.PtrToStructure(IntPtr, System.Type)
   at NLuaExperiments.KeraLuaTest.Start()
   at NLuaExperiments.Program.Main(System.String[])
using NLua;
using System;
using System.Runtime.InteropServices;

namespace NLuaExperiments
{
    public struct UserData
    {
        public object Ref;
    }

    public class KeraLuaTest
    {
        private Lua lua;
        public KeraLuaTest(Lua lua)
        {
            this.lua = lua;
        }

        public void Start()
        {
            KeraLua.Lua state = lua.State;

            IntPtr p = state.NewUserData(Marshal.SizeOf(default(UserData)));
            UserData u = (UserData)Marshal.PtrToStructure(p, typeof(UserData));
        }
    }

    class Program
    {
        private static Lua lua = new();

        static void Main(string[] args)
        {
            new KeraLuaTest(lua).Start();
        }
    }
}

Does NewUserData() does not provide a valid memory pointer to use as structure?

@viniciusjarina
Copy link
Member

To pass user data use ToObject and PushObject instead. https://github.com/NLua/KeraLua/blob/main/tests/Tests/Interop.cs#L50

@maikgreubel
Copy link
Author

Indeed! Thank you very much! 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants