2010-09-22 43 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

相關問題