包含传递给lua的std::string的结构 我使用Sigg工作C++代码,创建一个结构,将它传递给LUA(基本上是通过引用),并允许对结构进行操作,这样一旦我返回到C++函数,LUA代码中的更改就保留了。在我将std::string添加到结构之前,这一切都可以正常工作,如下所示: struct stuff { int x; int y; std::string z; };

包含传递给lua的std::string的结构 我使用Sigg工作C++代码,创建一个结构,将它传递给LUA(基本上是通过引用),并允许对结构进行操作,这样一旦我返回到C++函数,LUA代码中的更改就保留了。在我将std::string添加到结构之前,这一切都可以正常工作,如下所示: struct stuff { int x; int y; std::string z; };,c++,lua,swig,stdstring,C++,Lua,Swig,Stdstring,我无法修改std::string,因为它显然是作为常量引用传递的。如果我试图在lua函数中为该字符串赋值,则会出现以下错误: str(arg 2)中出错,应为'std::string const&'got'string' 解决这个问题的正确方法是什么?我是否需要编写一些自定义的C++函数来设置 z ,而不是使用普通语法,比如 Obj.z =“Hi”< /代码>?是否有某种方法允许使用swig进行此分配 > C++代码为 #include <stdio.h> #include &l

我无法修改std::string,因为它显然是作为常量引用传递的。如果我试图在lua函数中为该字符串赋值,则会出现以下错误:

str(arg 2)中出错,应为'std::string const&'got'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;

}

#包括
#包括
外部“C”{
#包括“lua.h”
#包括“lualib.h”
#包括“lauxlib.h”
}
#包括“示例_wrap.hxx”
外部输入luaopen_示例(lua_State*L);//声明包装的模块
int main()
{
字符buff[256];
const char*cmdstr=“打印(33)\n”;
整数误差;
lua_State*L=lua_open();
luaL_openlibs(L);
luaopen_示例(L);
结构材料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){
错误=luaL_加载缓冲区(L,buff,strlen(buff),“行”)||
lua_pcall(L,0,0,0);
如果(错误){
fprintf(标准,“%s”,lua_tostring(L,-1));
lua_pop(L,1);/*从堆栈中弹出错误消息*/
}
}
printf(“B.y现在%d\n”,B.y);
printf(“Str now%s\n”,b.Str.c_Str());
luaL_dostring(L,cmdstr);
卢厄关闭(L);
返回0;

}
您需要在SWIG模块中添加
%include
。否则,它不知道如何将Lua<代码>字符串映射到C++ >代码> STD::String < /C> > < /P>


我的.I文件中确实有这个;问题似乎是swig使字符串引用为常量,因此您无法更改它们。太棒了,类型映射解决了我的问题。非常感谢你的帮助!
%module example
%include "std_string.i"

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

struct my_struct
{
  std::string foo;
};