通过静态工厂方法创建内部结构的C++代码

2024-09-28 03:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有自己的C++,我想用pybdN11:

生成Python绑定。
auto markerParams = MarkerDetector::Params::create(MarkerType::chessboard);
markerDetector.detect(image, markerParams);

我在为MarkerDetector::Params结构生成绑定时遇到了问题,因为它是一个内部结构,使用一个以enum为参数的工厂方法构造:

^{pr2}$

有人知道如何处理这个更高级的案子吗?在


Tags: imageauto参数createenumparams结构detect
1条回答
网友
1楼 · 发布于 2024-09-28 03:19:54

我有一个基本的代码实现要运行,根据您的设计使用内部结构。为了简洁起见,我只包含了marketector和Params的相关细节,但它应该与您所做的匹配。在

c++代码:

#include <pybind11/pybind11.h>

namespace py = pybind11;

enum MarkerType { chessboard, tag };


class MarkerDetector {
    public:
    MarkerDetector() { }
    struct Params {
        int rows;
        int cols;
        static Params create(MarkerType markerType) {
            static Params markerTypes[] = {
                    { 1, 2 },
                    { 3, 4 }
            };
            return markerTypes[markerType];
        }
    };

};


PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example"; // optional module docstring

    py::enum_<MarkerType>(m, "MarkerType")
         .value("chessboard", MarkerType::chessboard)
         .value("tag",        MarkerType::tag)
         .export_values();

    py::class_<MarkerDetector>(m, "MarkerDetector")
            .def(py::init<>())
            ;

    py::class_<MarkerDetector::Params>(m, "MarkerDetectorParams")
            .def(py::init<>())
            .def_readwrite("rows", &MarkerDetector::Params::rows)
            .def_readwrite("cols", &MarkerDetector::Params::cols)
            .def("create", (MarkerDetector::Params (*)(MarkerType)) &MarkerDetector::Params::create)
            ;
}

(如果您感兴趣,可以使用命令行来编译上面的代码:)

^{pr2}$

python代码:

import sys
sys.path.append('/Volumes/Programs/workspaces/workspace 1/Project CPP 2')

import example

mtype = example.MarkerType.chessboard
print (mtype)

x = example.MarkerDetectorParams.create(example.MarkerType.chessboard)
print (x)
print (x.rows)
print (x.cols)

y = example.MarkerDetectorParams.create(example.MarkerType.tag)
print (y)
print (y.rows)
print (y.cols)

这将给出以下输出,根据设计,这些输出看起来是正确的:

MarkerType.chessboard
<example.MarkerDetectorParams object at 0x1043e35a8>
1
2
<example.MarkerDetectorParams object at 0x1043e3768>
3
4

我希望这能给你一些工作上的帮助。尊敬的,如

相关问题 更多 >

    热门问题