Skip to main content

c++/python类型映射

dict

我们将python中的dict映射到了c++中的dict:

#ifndef CUSTOM_DICT
using dict = std::shared_ptr<std::unordered_map<std::string, ipipe::any>>;
#else
// todo : custom dict with bidirectional binding between C++ and Python
#endif

c++ 到 python

基础类型转换

cpppython备注
std::stringbytes
cv::Matnumpy.ndarray
at::Tensortorch.Tensor
intint
floatfloat
doublefloat
unsigned intint
charstr继承自pybind11
unsigned charint
boolbool

容器转换

对于容器或者嵌套容器,转换规则如下(T为以上表格中的基础类型):

cpppython备注
std::unordered_map<std::string, T>dict[str, T]
std::unordered_set<T>set[T]T需要是可哈希的
std::vector<T>list[T]T不是代数类型
std::vector<T>numpy.ndarray[T]T为代数类型且不为bool
std::vector<std::vector<T>>list[numpy.ndarray[T]]T为代数类型且不为bool
std::map<std::string, T>不支持
std::set<T>不支持

类型嵌套

any转换为python类型还支持以下的类型嵌套

cpppython备注
std::vector<any>list[Any]可无穷层嵌套
std::unordered_map<std::string, any>dict[str, Any]可无穷层嵌套, 将忽略'data'键值

c++ wrapper

对于非容器,但是以上转换失败的类型,会返回一个自定义类型到python

cpppython备注
anytorchpipe.any

python 到 c++

基础类型转换

pythoncpp备注
strstd::string
bytesstd::string
numpy.ndarray不支持
torch.Tensorat::Tensor
boolbool
floatfloat会产生精度损失
intint

容器转换

对于容器或者嵌套容器,对照表如下(T为以上表格中的基础类型):

pythoncpp备注
dict[str, T]std::unordered_map<std::string, T>
set[T]std::unordered_set<T>T需要是可哈希的,也就是T != torch.Tensor
list[T]std::vector<T>

当python端的容器为空时,c++侧是无法感知具体类型的。此时,框架会以兼容的方式自动处理此类情况, 所以,使用时毋需额外关注此类情景。