简体   繁体   中英

SWIG how to access a byte array from a c struct in Lua using a Lua table to manipulate

I am trying to access a array in ac struct from Lua. I want to access it as byte array. I know I have to use typemaps somehow but I am not able to get it working like I want to.

the struct is defined within a namespace if that matter at all. For this example I call the headerfile send.h

namespace foo{
namespace bar{

typedef struct 
{
    ...
    unsigned char data[8];
} message;

}};

So I want to be able to access the unsigned char data array from the c struct from Lua. I want to access it like a table with numbers. Here my Lua script code I want to use.

modul = require("MyModule")
msg = modul.message()

msg.data[1] = 0x3b

print(msg.data[1])

All what I get is an error like "attempt to index field 'data' (a userdata value)" I did some research and found out that I have to add some kind of %typemap magic to deal with that. But I was not able to figure out exactly how.

So here my questions:

  • Can someone point me to a working example of that scenario?
  • What kind of typemap should I apply?
  • How can I apply such a typemap only to this struct and not to others?

So, finally I figured out that simple by using below typemap I'm able to access the data member just the way I want to. Hope that will help someone else.

%typemap(out) unsigned char foo::bar::message::data[8]
{
    int i;
    int32_t _size = 8;

    lua_newtable(L);
    for (i = 0; i < _size; i++)
    {
        lua_pushnumber(L, (lua_Number)$1[i]);
        lua_rawseti(L, -2, i + 1);
    }

    SWIG_arg++;
}

%include "send.h"
%{
#include "send.h"
%}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM