xeus 实现内核

xeus 实现内核#

在大多数情况下,基本的内核实现就足够了,创建内核仅仅意味着实现解释器部分。

你的项目结构至少应该看起来像这样:

└── example/
    ├── src/
    │   ├── custom_interpreter.cpp
    │   ├── custom_interpreter.hpp
    │   └── main.cpp
    ├── share/
    │   └── jupyter/
    │       └── kernels/
    │           └── my_kernel/
    │               └── kernel.json.in
    └── CMakeLists.txt

xeus-cookiecutter 项目提供了一个基于 xeus 的内核模板,并包含了基于 xeus 的内核的基本结构。

实现解释器#

从编辑 custom_interpreter.hpp 文件开始,它应该包含你的解释器类的声明:

/***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay, Martin Renou          *
* Copyright (c) 2016, QuantStack                                           *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef CUSTOM_INTERPRETER
#define CUSTOM_INTERPRETER

#include "xeus/xinterpreter.hpp"

#include "nlohmann/json.hpp"

using xeus::xinterpreter;

namespace nl = nlohmann;

namespace custom
{
    class custom_interpreter : public xinterpreter
    {
    public:

        custom_interpreter() = default;
        virtual ~custom_interpreter() = default;

    private:

        void configure_impl() override;

        void execute_request_impl(xrequest_context request_context,
                                  send_reply_callback cb,
                                  int execution_counter,
                                  const std::string& code,
                                  execute_request_config config,
                                  nl::json user_expressions) override;

        nl::json complete_request_impl(const std::string& code,
                                       int cursor_pos) override;

        nl::json inspect_request_impl(const std::string& code,
                                      int cursor_pos,
                                      int detail_level) override;

        nl::json is_complete_request_impl(const std::string& code) override;

        nl::json kernel_info_request_impl() override;

        void shutdown_request_impl() override;
    };
}

#endif

几乎所有 custom_interpreter 方法都返回 nl::json 实例。这实际上是在使用 nlohmann json,它是现代 C++ 实现的 JSON 数据结构。

用户可以选择使用回复 API,该 API 将适当地创建回复以发送到内核,或者自己创建回复。

待更:https://xeus.readthedocs.io/en/latest/kernel_implementation.html