是否可以通过dict将python dict传递给期望nlohmann::json (恩洛曼/杰森)对象的函数?这个问题现在应该已经提出来了,但我没能在上面找到任何东西。
(不考虑性能/安全,请原谅):
test-json.h
#include <iostream>
#include <nlohmann/json.hpp>
using nlohmann::json;
void print_name_and_age(json j) {
std::cout << j["name"] << "\n"
<< j["age"] << "\n";
} test-cppyy.py
import cppyy
cppyy.include('test-json.h')
from cppyy.gbl import print_name_and_age
some_dict = {
"name": "alfred",
"age": 25
}
print_name_and_age(some_dict)碰上
print_name_and_age(some_dict)
NotImplementedError: void ::print_name_and_age(nlohmann::json j) =>
NotImplementedError: could not convert argument 1 (this method cannot (yet) be called)我希望能够将python传递到C++函数中,并将其作为nlohmann::json对象接收。我想我需要为此写一些自定义转换器?
设计要求/背景(可选)
我有一个强化学习环境类(用C++编写),它需要接受一些配置来初始化它(在它的构造函数中)。在nlohmann::json域中将一个C++对象传递到构造函数中一切都很好,但我在类中也有一个Python包装器,它是用cppyy编写的,提供了与C++接口类似的功能。到目前为止,由于前面提到的问题,我不得不在构造函数中接收const std::map<std::string, float>&,而不是nlohmann::json,这就是nlohmann::json很容易被cppyy转换为只包含str -> float映射的python。但这显然限制了我的输入json文件仅包含floats作为值(我的usecase需要strings作为键,而strings、ints、floats和bools作为JSON文件中的值)。当然,我可以编写一些预处理代码,将我的异构python dict编码到python前端的一个统一的str->float映射中(并对C++做同样的操作),但如果可能的话,我想要一个更干净的解决方案。
谁能帮我实现将python dict传递到cppyy-imported C++函数并将其转换为C++函数中的nlohmann::json对象?如果这需要分叉cppyy来增加额外的转换器代码/太多的麻烦,我想我需要使用一个std::map<std::string, std::any / variant>替代?我没有经常使用std::any/variant,我想问一下这是否可能--从python dict到map<string, any> --这是否是自定义转换器的最佳替代方案-- in terms of performance /干净优雅的代码。
Environment:
Python 3.9.13
C++17 (我相信cppyy-2.4.0还不支持C++20,我对C++标准没有任何限制)
cppyy==2.3.1
cppyy-backend==1.14.8
cppyy-cling==6.25.3
cppyythonizations==1.2.1MacOS蒙特里,苹果M1
发布于 2022-09-30 11:35:14
这已经在nlohmann::json上得到了回答。
https://stackoverflow.com/questions/73623404
复制相似问题