python - 在 C++ 和 Python 程序之间共享数据的最快方法?
问题描述
我正在尝试构建一个算法交易程序。该程序的执行流程如下:
Server sends data via websocket -> Python program receives it and sends it to C++ program -> C++ program processes the data and sends some data to Python code -> Python code sends packets to Server
我没有在 C++ 中构建整个东西的原因是因为 Broker 的 API 仅支持 Python,如果我切换到 Python,我无法执行我希望足够快地执行的操作。
数据的频率将至少为每秒约 50kb(二进制和 Json)。到目前为止,我找到了以下替代方案:
在 C++ 代码中嵌入 Python。这看起来很棒,但我不确定是否能够在 C++ 中导入整个库并使用类/方法(经纪人的客户端)。
通过发送数据包进行通信(这里的问题是延迟)
将接收到的数据放入 SQL 数据库中,并让 C++ 每 X 毫秒查询一次。(再次,延迟)
有没有更好的方法来做到这一点?
解决方案
如果您使用的是 CPython(python 最常见的实现),那么您可以创建一个可用作 python 模块的动态库。有 Boost.Python
可以用作:
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
> import hello_ext
> print(hello_ext.greet())
hello, world
要使用 python 3.7 和 boost 1.68.0 构建,您可以使用以下 CMake 文件
cmake_minimum_required(VERSION 3.9.0 FATAL_ERROR)
project("boost_python_sample" LANGUAGES CXX)
set(BOOST_ROOT "C:/local/boost_1_68_0")
find_package(Boost REQUIRED COMPONENTS python37)
set(Python3_ROOT_DIR "C:/python37")
find_package(Python3 REQUIRED COMPONENTS Development)
add_library("boost_python_sample" SHARED "main.cpp")
target_link_libraries("boost_python_sample" Boost::python37 Python3::Python)
target_compile_definitions("boost_python_sample" PUBLIC "BOOST_PYTHON_STATIC_LIB")
推荐阅读
- matlab - 为 Matlab 编写 Astropy 单元/什么是软件架构?
- button - 如何在输入类型按钮中添加图像
- javascript - 如何访问 JavaScript 数组中的一个对象的值之一?
- tpm - TPM 命令 CreatePrimary UEFI 应用程序
- html - div背景图像中的html幻灯片
- java - Android:在 ExternalStorage 上使用文件提供程序
- node.js - Node.js 中的异步响应
- sql-server - 如何在子句中按大小写排序列表(SQL Server)
- reactjs - Recharts 饼图 .. 选择时饼图可以移动吗?
- reactjs - 反应路由器路径问题