2010-09-22 87 views
2

我有工作C++代码使用swig创建一个结构,将其传递给lua(实质上通过引用),并允许对结构进行操作,使得在lua代码中所做的更改一旦我返回到C++函数就保留下来。直到我添加的std :: string的struct这一切工作正常,如下所示:将包含std :: string的结构传递给lua

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

我无法修改的std :: string,因为它是作为一个const引用传递明显。如果我试图在我的LUA函数赋值给这个字符串我得到这个错误:

Error in str (arg 2), expected '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; 

}

回答

4

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


A common problem that people encounter is that of classes/structures containing a std::string. This can be overcome by defining a typemap. For example:

%module example 
%include "std_string.i" 

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

struct my_struct 
{ 
    std::string foo; 
}; 
+0

我做我的。我的文件有这样的;该问题似乎是swig使字符串常量引用,所以你不能改变它们。 – alanc10n 2010-09-22 19:26:03

+0

神奇的是,typemap解决了我的问题。非常感谢你的帮助! – alanc10n 2010-09-22 21:50:07