gpt4 book ai didi

c++ - std::bind 不能与 lua_call 互操作

转载 作者:行者123 更新时间:2023-12-01 23:43:30 26 4
gpt4 key购买 nike

使用 Lua 5.3.5 和 gcc 9.2.0 的开发库时,我遇到了以下最小代码片段的奇怪编译问题:

#include <functional>

extern "C" {
#include "lua.h"
#include "lualib.h"
}

int main()
{
using namespace std::placeholders;

auto lua_simple_call = std::bind(lua_call, _1, 0, 0);
}

gcc 提示:错误:“lua_call”未在此范围内声明。当尝试简单地调用 lua_call 而不使用 std::bind 时,不会出现此问题,并且对于其他 Lua C 函数(如 )似乎也不会出现此问题lua_newtable 等。我想知道是什么原因造成的以及如何规避它。

最佳答案

正如OP提到的,lua_call是一个扩展为lua_callk的宏,但这只是事实的一半。

lua_call 是一个函数宏:

github: lua.h:

#define lua_call(L,n,r)     lua_callk(L, (n), (r), 0, NULL)

这就是不同之处。

因此,仅当与正确数量的参数一起使用时,lua_call 才会扩展为 lua_callk

我制作了一个 MCVE 来演示这一点:

#include <iostream>

#define lua_call(L, n, r) lua_callk(L, (n), (r))

void lua_callk(void *L, int n, int r)
{
std::cout << "lua_callk(" << L << ", " << n << ", " << r << ")\n";
}

#define TEST(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__

int main()
{
TEST(lua_call(nullptr, 2, 1));
//TEST(std::cout << "&lua_call: " << &lua_call << '\n');
}

输出:

g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
lua_call(nullptr, 2, 1);
lua_callk(0, 2, 1)

Live Demo on coliru

对比:

#include <iostream>

#define lua_call(L, n, r) lua_callk(L, (n), (r))

void lua_callk(void *L, int n, int r)
{
std::cout << "lua_callk(" << L << ", " << n << ", " << r << ")\n";
}

#define TEST(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__

int main()
{
TEST(lua_call(nullptr, 2, 1));
std::cout << "&lua_call: " << &lua_call << '\n');
}

输出:

main.cpp: In function 'int main()':
main.cpp:15:34: error: 'lua_call' was not declared in this scope
15 | std::cout << "&lua_call: " << &lua_call << '\n';
| ^~~~~~~~

Live Demo on coliru

或者,为了让这一点更加明显:

//#include <iostream>

#define lua_call(L, n, r) lua_callk(L, (n), (r))

void lua_callk(void *L, int n, int r)
{
std::cout << "lua_callk(" << L << ", " << n << ", " << r << ")\n";
}

#define TEST(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__

int main()
{
TEST(lua_call(nullptr, 2, 1));
std::cout << "&lua_call: " << &lua_call << '\n';
}

仅运行预处理器:

# 1 "main.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.cpp"


void lua_callk(void *L, int n, int r)
{
std::cout << "lua_callk(" << L << ", " << n << ", " << r << ")\n";
}


int main()
{
std::cout << "lua_call(nullptr, 2, 1)" << ";\n"; lua_callk(nullptr, (2), (1));
std::cout << "&lua_call: " << &lua_call << '\n';
}

Live Demo on coliru

<小时/>

修复方法也很明显(如 Rafix' comment 中已经提到的):

只需将 lua_bind() 包装成可寻址的东西:函数或 lambda。

关于c++ - std::bind 不能与 lua_call 互操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60635927/

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