gpt4 book ai didi

c++ - 包含 std::string 的结构被传递给 lua

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:29 25 4
gpt4 key购买 nike

我有使用 swig 的工作 C++ 代码,它创建一个结构,将它传递给 lua(基本上通过引用),并允许操作该结构,以便在我返回到 C++ 函数后保留在 lua 代码中所做的更改.在我将 std::string 添加到结构之前,这一切都很好,如下所示:

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

我无法修改 std::string,因为它显然是作为常量引用传递的。如果我试图在我的 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;

}

最佳答案

您需要添加 %include <std_string.i>到您的 SWIG 模块。否则,它不知道如何映射 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;
};

关于c++ - 包含 std::string 的结构被传递给 lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3771784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com