C++ interpreter: first crash when invoking native callback

This was a regression following the move to the edition 2021.
The CallbackUserData was not capture in the lamda, its member were moved.
So the destructor was called right after it was set.
We must make sure we capture the whole CallbackUserData, so put the callback
inside of it. This also reduce a bit of code duplication at the same time.

Test the callback invokation with statefull lambda
This commit is contained in:
Olivier Goffart 2022-01-31 22:11:21 +01:00
parent 0d358251c9
commit f9c3e7a8de
2 changed files with 25 additions and 20 deletions

View file

@ -359,16 +359,17 @@ SCENARIO("Invoke callback")
"export Dummy := Rectangle { callback some_callback(string, int) -> string; }", "");
REQUIRE(result.has_value());
auto instance = result->create();
REQUIRE(instance->set_callback("some_callback", [](auto args) {
std::string local_string = "_string_on_the_stack_";
REQUIRE(instance->set_callback("some_callback", [local_string](auto args) {
SharedString arg1 = *args[0].to_string();
int arg2 = int(*args[1].to_number());
std::string res = std::string(arg1) + ":" + std::to_string(arg2);
std::string res = std::string(arg1) + ":" + std::to_string(arg2) + local_string;
return Value(SharedString(res));
}));
Value args[] = { SharedString("Hello"), 42. };
auto res = instance->invoke_callback("some_callback", args);
REQUIRE(res.has_value());
REQUIRE(*res->to_string() == SharedString("Hello:42"));
REQUIRE(*res->to_string() == SharedString("Hello:42_string_on_the_stack_"));
}
SECTION("invalid")