私は swig を使用して構造体を作成し、それを (基本的に参照によって) lua に渡し、C++ 関数に戻った後も lua コードで行われた変更が残るように構造体を操作できるようにする C++ コードを使用しています。次に示すように、構造体に std::string を追加するまで、これはすべて正常に機能します。
struct stuff
{
int x;
int y;
std::string z;
};
std::string は明らかに const 参照として渡されているため、変更できません。lua 関数でこの文字列に値を割り当てようとすると、次のエラーが発生します。
str のエラー (引数 2)、予期された 'std::string const &' が 'string' を取得しました
この問題に対処する適切な方法は何ですか? z
のような通常の構文を使用するのではなく、設定するカスタム C++ 関数を作成する必要があります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;
}