forked from chronolaw/cpp_study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpybind.cpp
More file actions
139 lines (115 loc) · 2.58 KB
/
pybind.cpp
File metadata and controls
139 lines (115 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Copyright (c) 2020 by Chrono
//
// apt install python3-pip
// pip3 install pybind11
//
// apt install python3-dev
// mkdir build && cd build
// cmake .. -DPYBIND11_TEST=OFF
//
// g++ pybind.cpp -std=c++11 -shared -fPIC `python3 -m pybind11 --includes` -o pydemo`python3-config --extension-suffix`
// g++ pybind.cpp -std=c++14 -shared -fPIC `python3 -m pybind11 --includes` -o pydemo`python3-config --extension-suffix`
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
using namespace std;
namespace py = pybind11;
class Point final
{
private:
int x = 0;
public:
Point() = default;
~Point() = default;
Point(int a) : x(a) {}
public:
int get() const
{
return x;
}
void set(int a)
{
x = a;
}
};
PYBIND11_MODULE(pydemo, m)
{
m.doc() = "pybind11 demo doc";
m.def("info",
[]()
{
//cout << "c++ version = " << __cplusplus << endl;
//cout << "gcc version = " << __VERSION__ << endl;
//cout << "libstdc++ = " << __GLIBCXX__ << endl;
py::print("c++ version =", __cplusplus);
py::print("gcc version =", __VERSION__);
py::print("libstdc++ =", __GLIBCXX__);
}
);
m.def("add",
[](int a, int b)
{
return a + b;
}
);
m.def("use_str",
[](const string& str)
{
//cout << str << endl;
py::print(str);
return str + "!!";
}
);
m.def("use_tuple",
[](tuple<int, int, string> x)
{
get<0>(x)++;
get<1>(x)++;
get<2>(x)+= "??";
return x;
}
);
m.def("use_list",
[](const vector<int>& v)
{
auto vv = v;
//for(auto& x : vv) {
// //cout << x << ",";
//}
//cout << endl;
py::print("input :", vv);
vv.push_back(100);
return vv;
}
);
py::class_<Point>(m, "Point")
.def(py::init())
.def(py::init<int>())
.def("get", &Point::get)
.def("set", &Point::set)
;
}
#if 0
void info()
{
cout << "c++ version = " << __cplusplus << endl;
cout << "gcc version = " << __VERSION__ << endl;
cout << "libstdc++ = " << __GLIBCXX__ << endl;
}
int add(int a, int b)
{
return a + b;
}
PYBIND11_MODULE(pydemo, m)
{
m.doc() = "pybind11 demodoc";
m.def("info", &info, "cpp info");
m.def("add", &add, "add func");
}
#endif
#if 0
int main()
{
cout << "pybind demo" << endl;
}
#endif