python - _IO_FILE 的 Pybind11 文件指针包装器
问题描述
我正在为接受文件指针的 c++ 类编写 python 绑定 -
PYBIND11_MODULE(pywrapper, m) {
...
py::class_<Dog, Animal>(m, "Dog")
.def(py::init<FILE * const>());
}
我这样调用c++函数-
f = open("test.log","w")
c = Dog(f)
我收到了预期的错误-
File "main.py", line 6, in test_init
client = Dog(f)
TypeError: __init__(): incompatible constructor arguments. The following argument types are supported:
1. pywrapper.Dog(arg0: _IO_FILE)
Invoked with: <_io.TextIOWrapper name='test.log' mode='w' encoding='UTF-8'>
我如何在这里为构造函数编写包装器?
解决方案
我相信输入缓冲区没有在 pybind11 中实现。这是输出缓冲区的实现https://github.com/pybind/pybind11/blob/master/include/pybind11/iostream.h#L24
以下是使用缓冲区作为输出流的示例:
.def("read_from_file_like_object",
[](MyClass&, py::object fileHandle) {
if (!(py::hasattr(fileHandle,"write") &&
py::hasattr(fileHandle,"flush") )){
throw py::type_error("MyClass::read_from_file_like_object(file): incompatible function argument: `file` must be a file-like object, but `"
+(std::string)(py::repr(fileHandle))+"` provided"
);
}
py::detail::pythonbuf buf(fileHandle);
std::ostream stream(&buf);
//... use the stream
},
py::arg("buf")
)
推荐阅读
- ios - 使用苹果在权限消息中缺少应用名称登录
- bash - 将 Makefile 中命令的结果存储在变量中
- android-layout - 背景和文本颜色交互
- android-custom-view - 为什么自定义菜单图标没有响应
- html - Bootstrap CSS - 在较小的断点处浮动的行
- api - goroutines 与数据列表并行运行 post api
- amazon-ec2 - 来自 EC2 资源的 Terraform 远程执行主机 IP 已构建
- node.js - Firebase 管理员查询:collection where documentId() IN Array of ids
- flutter - 小部件文本中的 TextOverFlow.ellipsis 不起作用
- sql - 如何创建用于标记夏令时额外时间的唯一值?