传递包含std::string的结构到lua。

我有一个可以使用swig创建一个结构体的工作C++代码,将其传递给lua(基本上通过引用),并允许操作结构体,使得在我返回到C++函数后在lua代码中所做的更改保留。这一切都很好,直到我向结构添加了std :: string,如下所示:

struct stuff
{
    int x;
    int y;
    std::string z;
};

我无法修改std :: string,因为它显然被传递为常量引用。如果我尝试在lua函数中为此字符串分配一个值,我会得到以下错误:

在str(arg 2)中的错误,期望'std :: string const&',得到'string'

如何解决这个问题?我必须编写一些自定义C ++函数来设置z,而不是使用obj.z =“hi”之类的正常语法吗?是否有一种使用swig允许进行此赋值的方法?

该C ++代码为

#include <stdio.h>
#include <string.h>
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

#include "example_wrap.hxx"

extern int luaopen_example(lua_State* L); // declare the wrapped module

int main()
{

    char buff[256];
    const char *cmdstr = "print(33)\n";
    int error;
    lua_State *L = lua_open();
    luaL_openlibs(L);
    luaopen_example(L);

    struct stuff b;

    b.x = 1;
    b.y = 2;

    SWIG_NewPointerObj(L, &b, SWIGTYPE_p_stuff, 0);
    lua_setglobal(L, "b");

     while (fgets(buff, sizeof(buff), stdin) != NULL) {
        error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
                lua_pcall(L, 0, 0, 0);
        if (error) {
          fprintf(stderr, "%s", lua_tostring(L, -1));
          lua_pop(L, 1);  /* pop error message from the stack */
        }
      }

      printf("B.y now %d\n", b.y);
      printf("Str now %s\n", b.str.c_str());
      luaL_dostring(L, cmdstr);
      lua_close(L);
      return 0;

}

原文链接 https://stackoverflow.com/questions/3771784

点赞
stackoverflow用户1491
stackoverflow用户1491

你需要在你的 SWIG 模块中添加 %include <std_string.i>。否则,它不知道如何将 Lua 的 string 映射到 C++ 的 std::string


人们经常遇到的一个常见问题是包含 std::string 的类/结构。这可以通过定义类型映射来解决。例如:

%module example
%include "std_string.i"

%apply const std::string& {std::string* foo};

struct my_struct
{
  std::string foo;
};
2010-09-22 18:47:27