简体   繁体   English

SWIG如何使用Lua表从Lua中的ac struct访问字节数组

[英]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. 我正在尝试从Lua访问ac struct中的数组。 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. 我知道我必须以某种方式使用typemap,但是我无法像我想要的那样使它工作。

the struct is defined within a namespace if that matter at all. 如果有关系的话,该结构是在名称空间中定义的。 For this example I call the headerfile send.h 对于此示例,我将头文件称为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. 因此,我希望能够从Lua的c结构访问未签名的char数据数组。 I want to access it like a table with numbers. 我想像访问带有数字的表格一样访问它。 Here my Lua script code I want to use. 这是我要使用的Lua脚本代码。

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. 我得到的只是一个错误,例如“试图索引字段'data'(一个userdata值)”。我进行了一些研究,发现我必须添加某种%typemap魔术来进行处理。 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. 因此,最后,我通过使用下面的typemap找出了一个简单的方法,便可以按照我想要的方式访问数据成员。 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"
%}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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