4

我有一个类 Foo() 并且类 Foo() 有一个具有以下声明的函数:

bool Foo::copyFile(const std::filesystem::path& src, const std::filesystem::path& dest)

要求是类 Foo 应该具有 Python 绑定。我正在使用 pybind11 创建 Python 绑定。

我编写了以下内容来创建 Python 绑定:

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "Foo.h"

namespace py = pybind11;

PYBIND11_MODULE(TestModule, m) {
     py::class_ <Foo>(m, "Foo")
        .def(py::init())
        .def("copyFile",&Foo::copyFile);
};

这可以编译,我可以创建 Python 绑定 pyd 文件。当我使用 Foo 类的 Python 绑定时,使用:

from TestModule import Foo

f = Foo()
ret = f.copyFile("C:\Users\csaikia\Downloads\testfile_src", "C:\Users\csaikia\Downloads\testfile_dest")

它给出了一个 TypeError。我怀疑它与 pybind11 对 c++17 中 std::filesystem 的支持有关,因为我没有看到具有std::stringor的类的其他函数会发生这种情况std::vector

我得到的错误是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: copyFile(): incompatible function arguments. The following argument types are supported:
    1. (self: TestModule.Foo, arg0: std::filesystem::path, arg1: std::filesystem::path) -> bool

Invoked with: <TestModule.Foo object at 0x0000000002A33ED8>,  'C:\\Users\\csaikia\\Downloads\\testfile_src', 'C:\\Users\\csaikia\\Downloads\\testfile_dest'

Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,
<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic
conversions are optional and require extra headers to be included
when compiling your pybind11 module.

我是 pybind11 的新手。有人可以帮我解决这个问题吗?

4

2 回答 2

4

从我与 pybind11 开发人员的对话中:

“Pybind 不知道如何将 a 转换py::strstd::filesystem::path。没有可用的施法者,也没有std::filesystem::path绑定类。

最简单的方法是不Foo::copyFile直接绑定。而是绑定一个接受const Foo&const std::string&作为参数的 lambda,然后您可以传递std::string到预期的copyFile位置std::filesystem::path,让 C++ 隐式转换发生。

你也可以py::class_<std::filesystem::path>为转换器做一个绑定,std::string然后用它py::implicitly_convertible来让所有 C++ 隐式构造发生在 python 端,但是……嗯,工作太多了。”

它就像一个魅力!

于 2019-05-06T18:23:44.677 回答
1

只需将以下行添加到您的绑定中(假设py::module& m)。

py::class_<std::filesystem::path>(m, "Path")
    .def(py::init<std::string>());
py::implicitly_convertible<std::string, std::filesystem::path>();

这是基于@user304255 描述的后一种方法。

于 2020-04-21T09:33:34.600 回答