题
我使用创建结构的SWIG进行了工作C ++代码,将其传递给LUA(本质上是参考),并允许操纵结构,以使LUA代码中所做的更改一旦我返回C ++函数。这一切都很好,直到我将std ::字符串添加到结构上,如下所示:
struct stuff
{
int x;
int y;
std::string z;
};
我无法修改std ::字符串,因为它显然是作为const引用传递的。如果我尝试在我的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;
}
解决方案
您需要添加 %include <std_string.i>
到您的SWIG模块。否则,它不知道如何映射lua string
到C ++ std::string
.
%module example
%include "std_string.i"
%apply const std::string& {std::string* foo};
struct my_struct
{
std::string foo;
};
不隶属于 StackOverflow