Pass pointer to const, and return vector of pointers


#1

I am trying to pass a shared_ptr<const Event> to a ChaiScript function, but I get a bad any cast error when trying to get the return value of vector<Event>.

The following program works when passing an Event_ptr, but fails when passing a Const_event_ptr.

    #include <iostream>
    #include <functional>
    #include <string>
    #include <vector>
    #include <memory>
    #include <chaiscript/chaiscript.hpp>

    auto chaiscipt_text = R"_(
    def process_event(Event input_event) 
    { 
    	print(input_event.s);
    	//input_event.s = "New string";

    	auto output_events = Output_events();
    	for(var b = input_event.i; b > 0 ; --b)
    	{
    		auto output_event = Event();
    		output_event.s = "String set in script";
    		output_event.i = b;
    		output_events.push_back(output_event);
    	}
    	return output_events;
    }
    )_";

    struct Event{
    	Event() = default;
    	std::string s{"default string"};
    	int i{4};
    };

    using Event_ptr = std::shared_ptr<Event>;
    using Const_event_ptr = std::shared_ptr<const Event>;

    struct Program{
    	using Output_events = std::vector<Event_ptr>;
    	using Processing_function = std::function <Output_events(Const_event_ptr)>; // results in 'bad any cast' error
    	//using Processing_function = std::function <Output_events(Event_ptr)>; // works, but input event is mutable

    	Program()
    	{
    		chai.add(chaiscript::user_type<Event>(), "Event");
    		chai.add(chaiscript::bootstrap::standard_library::vector_type<Output_events>("Output_events"));
    		chai.add(chaiscript::constructor<Event(void)>(), "Event");
    		chai.add(chaiscript::fun(&Event::s), "s");
    		chai.add(chaiscript::fun(&Event::i), "i");
    		try{
    			chai.eval(chaiscipt_text);
    			f = chai.eval<Processing_function>("process_event");
    		}
    		catch(const chaiscript::exception::eval_error &e){
    			std::cout << "Error\n" << e.pretty_print() << '\n';
    		}
    	}
    	Processing_function f{};
    	chaiscript::ChaiScript chai;
    };

    int main()
    {
    	try{
    		Program program{};
    		auto event_ptr{std::make_shared<Event>()};
    		auto result = program.f(event_ptr);
    		for(auto& evt : result)
    			std::cout << evt->i << ' ';
    		std::cout << '\n';
    	}
    	catch(const chaiscript::exception::eval_error &e){
    		std::cout << "Error\n" << e.pretty_print() << '\n';
    	}
    	catch(const std::exception &e){
    		std::cout << e.what() << '\n';
    	}
    }

What is the best way to pass a pointer to const and receive back a vector of pointers to mutable values?