├── .gitignore
├── .gitmodules
├── CMakeLists.txt
├── LICENSE
├── Readme.md
├── boost_wrap
└── boost_python.cpp
├── cMake
├── FindCython.cmake
└── UseCython.cmake
├── cppyy_wrap
├── CMakeLists.txt
└── test_cppyy.py
├── cython_wrap
├── CMakeLists.txt
├── Rectangle.pxd
├── setup.py
└── shapes_cython.pyx
├── pybind11_wrap
├── CMakeLists.txt
├── setup.py
└── shapes_pybind11.cpp
├── src
├── CMakeLists.txt
├── Rectangle.cpp
└── Rectangle.h
├── swig_wrap
├── CMakeLists.txt
├── example.i
└── setup.py
└── test
└── test_shapes.py
/.gitignore:
--------------------------------------------------------------------------------
1 | pybind11_binder/*
2 | */build/*
3 | *.pyc
4 | *.so
5 | lib/*
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "pybind11_binder/binder"]
2 | path = pybind11_binder/binder
3 | url = https://github.com/RosettaCommons/binder.git
4 | [submodule "pybind11_wrap/pybind11"]
5 | path = pybind11_wrap/pybind11
6 | url = https://github.com/pybind/pybind11.git
7 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #
2 | # copyright Qingfeng Xia 2019
3 | # CC BY 4.0
4 | #
5 |
6 | cmake_minimum_required(VERSION 3.0)
7 | project("python wrap interoperation")
8 |
9 | # name shared by subdirectories cmakelists.txt
10 | set(MY_PYBIND11_WRAP "shapes_pybind11")
11 | set(MY_SHARED_LIB "shapes")
12 | set(MY_MODULE "shapes")
13 |
14 | SET( CMAKE_BUILD_TYPE Debug)
15 | add_definitions("-DCMAKE_BUILD_TYPE=Debug")
16 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
17 |
18 | # can be set to C++14, 17 on a newer std
19 | set(CMAKE_CXX_STANDARD 11)
20 | set(CMAKE_CXX_STANDARD_REQUIRED ON)
21 | set(PYBIND11_CPP_STANDARD -std=c++11)
22 |
23 | #extra cmake module provided by this repo
24 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
25 | "${CMAKE_CURRENT_SOURCE_DIR}/cMake"
26 | "${CMAKE_CURRENT_SOURCE_DIR}/pybind11_wrap/tools/"
27 | )
28 |
29 | ######################################
30 | # options
31 | ######################################
32 | option(USE_CYTHON "use cython" ON)
33 | option(USE_PYBIND11 "use pybind11" ON)
34 | option(USE_CPPYY "use cppyy" OFF)
35 | option(USE_SWIG "use swig to generate interface code" OFF) # error not fixed
36 | option(USE_BINDER "use binder to generate pybind11 wrap code" OFF)
37 |
38 |
39 | find_package(Python3 COMPONENTS Interpreter Development)
40 | if (NOT ${PYTHON_VERSION_STRING})
41 | find_package(PythonLibsNew 3 REQUIRED)
42 | endif()
43 | message(STATUS "Found Python: ${PYTHON_EXECUTABLE} (found version \"${PYTHON_VERSION_STRING}\")")
44 |
45 | # cross OS setup
46 | IF(WIN32)
47 | # windows
48 | SET(WINDOWS_EXPORT_ALL_SYMBOLS ON)
49 | SET(PY_EXTENSION "dll")
50 | ELSE()
51 | SET(PY_EXTENSION "so")
52 | ENDIF()
53 |
54 | ## put all targets in bin
55 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)
56 | ## put all libraries in lib
57 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib)
58 |
59 | link_directories(${CMAKE_LIBRARY_OUTPUT_DIRECTORY})
60 |
61 | ######################################
62 | # c++ shared library to be wrapped
63 | ######################################
64 | add_subdirectory("src")
65 |
66 | if(USE_BINDER)
67 | ######################################
68 | # binder use a modified pybind11
69 | ######################################
70 | add_subdirectory(pybind11_binder)
71 | endif()
72 |
73 | if(USE_PYBIND11)
74 | ######################################
75 | # pybind11 wrap
76 | ######################################
77 | add_subdirectory("pybind11_wrap")
78 | endif()
79 |
80 | ######################################
81 | # swig build
82 | # cmake and setup.py are both provided in subdir
83 | ######################################
84 | if(USE_SWIG)
85 | add_subdirectory("swig_wrap")
86 | endif()
87 |
88 | ######################################
89 | # cython build
90 | # cmake and setup.py are both provided in subdir
91 | ######################################
92 | if(USE_CYTHON)
93 | add_subdirectory("cython_wrap")
94 | endif()
95 |
96 | ######################################
97 | # cppyy build
98 | # cmake and setup.py are both provided in subdir
99 | ######################################
100 | if(USE_CPPYY)
101 | add_subdirectory("cppyy_wrap")
102 | endif()
103 |
104 |
105 | ######################################
106 | # test
107 | ######################################
108 |
109 | #file(COPY "${PROJECT_SOURCE_DIR}/test/test_*.py"
110 | # DESTINATION ${PROJECT_BINARY_DIR}
111 | # )
112 |
113 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Attribution-ShareAlike 4.0 International
2 |
3 | =======================================================================
4 |
5 | Creative Commons Corporation ("Creative Commons") is not a law firm and
6 | does not provide legal services or legal advice. Distribution of
7 | Creative Commons public licenses does not create a lawyer-client or
8 | other relationship. Creative Commons makes its licenses and related
9 | information available on an "as-is" basis. Creative Commons gives no
10 | warranties regarding its licenses, any material licensed under their
11 | terms and conditions, or any related information. Creative Commons
12 | disclaims all liability for damages resulting from their use to the
13 | fullest extent possible.
14 |
15 | Using Creative Commons Public Licenses
16 |
17 | Creative Commons public licenses provide a standard set of terms and
18 | conditions that creators and other rights holders may use to share
19 | original works of authorship and other material subject to copyright
20 | and certain other rights specified in the public license below. The
21 | following considerations are for informational purposes only, are not
22 | exhaustive, and do not form part of our licenses.
23 |
24 | Considerations for licensors: Our public licenses are
25 | intended for use by those authorized to give the public
26 | permission to use material in ways otherwise restricted by
27 | copyright and certain other rights. Our licenses are
28 | irrevocable. Licensors should read and understand the terms
29 | and conditions of the license they choose before applying it.
30 | Licensors should also secure all rights necessary before
31 | applying our licenses so that the public can reuse the
32 | material as expected. Licensors should clearly mark any
33 | material not subject to the license. This includes other CC-
34 | licensed material, or material used under an exception or
35 | limitation to copyright. More considerations for licensors:
36 | wiki.creativecommons.org/Considerations_for_licensors
37 |
38 | Considerations for the public: By using one of our public
39 | licenses, a licensor grants the public permission to use the
40 | licensed material under specified terms and conditions. If
41 | the licensor's permission is not necessary for any reason--for
42 | example, because of any applicable exception or limitation to
43 | copyright--then that use is not regulated by the license. Our
44 | licenses grant only permissions under copyright and certain
45 | other rights that a licensor has authority to grant. Use of
46 | the licensed material may still be restricted for other
47 | reasons, including because others have copyright or other
48 | rights in the material. A licensor may make special requests,
49 | such as asking that all changes be marked or described.
50 | Although not required by our licenses, you are encouraged to
51 | respect those requests where reasonable. More considerations
52 | for the public:
53 | wiki.creativecommons.org/Considerations_for_licensees
54 |
55 | =======================================================================
56 |
57 | Creative Commons Attribution-ShareAlike 4.0 International Public
58 | License
59 |
60 | By exercising the Licensed Rights (defined below), You accept and agree
61 | to be bound by the terms and conditions of this Creative Commons
62 | Attribution-ShareAlike 4.0 International Public License ("Public
63 | License"). To the extent this Public License may be interpreted as a
64 | contract, You are granted the Licensed Rights in consideration of Your
65 | acceptance of these terms and conditions, and the Licensor grants You
66 | such rights in consideration of benefits the Licensor receives from
67 | making the Licensed Material available under these terms and
68 | conditions.
69 |
70 |
71 | Section 1 -- Definitions.
72 |
73 | a. Adapted Material means material subject to Copyright and Similar
74 | Rights that is derived from or based upon the Licensed Material
75 | and in which the Licensed Material is translated, altered,
76 | arranged, transformed, or otherwise modified in a manner requiring
77 | permission under the Copyright and Similar Rights held by the
78 | Licensor. For purposes of this Public License, where the Licensed
79 | Material is a musical work, performance, or sound recording,
80 | Adapted Material is always produced where the Licensed Material is
81 | synched in timed relation with a moving image.
82 |
83 | b. Adapter's License means the license You apply to Your Copyright
84 | and Similar Rights in Your contributions to Adapted Material in
85 | accordance with the terms and conditions of this Public License.
86 |
87 | c. BY-SA Compatible License means a license listed at
88 | creativecommons.org/compatiblelicenses, approved by Creative
89 | Commons as essentially the equivalent of this Public License.
90 |
91 | d. Copyright and Similar Rights means copyright and/or similar rights
92 | closely related to copyright including, without limitation,
93 | performance, broadcast, sound recording, and Sui Generis Database
94 | Rights, without regard to how the rights are labeled or
95 | categorized. For purposes of this Public License, the rights
96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
97 | Rights.
98 |
99 | e. Effective Technological Measures means those measures that, in the
100 | absence of proper authority, may not be circumvented under laws
101 | fulfilling obligations under Article 11 of the WIPO Copyright
102 | Treaty adopted on December 20, 1996, and/or similar international
103 | agreements.
104 |
105 | f. Exceptions and Limitations means fair use, fair dealing, and/or
106 | any other exception or limitation to Copyright and Similar Rights
107 | that applies to Your use of the Licensed Material.
108 |
109 | g. License Elements means the license attributes listed in the name
110 | of a Creative Commons Public License. The License Elements of this
111 | Public License are Attribution and ShareAlike.
112 |
113 | h. Licensed Material means the artistic or literary work, database,
114 | or other material to which the Licensor applied this Public
115 | License.
116 |
117 | i. Licensed Rights means the rights granted to You subject to the
118 | terms and conditions of this Public License, which are limited to
119 | all Copyright and Similar Rights that apply to Your use of the
120 | Licensed Material and that the Licensor has authority to license.
121 |
122 | j. Licensor means the individual(s) or entity(ies) granting rights
123 | under this Public License.
124 |
125 | k. Share means to provide material to the public by any means or
126 | process that requires permission under the Licensed Rights, such
127 | as reproduction, public display, public performance, distribution,
128 | dissemination, communication, or importation, and to make material
129 | available to the public including in ways that members of the
130 | public may access the material from a place and at a time
131 | individually chosen by them.
132 |
133 | l. Sui Generis Database Rights means rights other than copyright
134 | resulting from Directive 96/9/EC of the European Parliament and of
135 | the Council of 11 March 1996 on the legal protection of databases,
136 | as amended and/or succeeded, as well as other essentially
137 | equivalent rights anywhere in the world.
138 |
139 | m. You means the individual or entity exercising the Licensed Rights
140 | under this Public License. Your has a corresponding meaning.
141 |
142 |
143 | Section 2 -- Scope.
144 |
145 | a. License grant.
146 |
147 | 1. Subject to the terms and conditions of this Public License,
148 | the Licensor hereby grants You a worldwide, royalty-free,
149 | non-sublicensable, non-exclusive, irrevocable license to
150 | exercise the Licensed Rights in the Licensed Material to:
151 |
152 | a. reproduce and Share the Licensed Material, in whole or
153 | in part; and
154 |
155 | b. produce, reproduce, and Share Adapted Material.
156 |
157 | 2. Exceptions and Limitations. For the avoidance of doubt, where
158 | Exceptions and Limitations apply to Your use, this Public
159 | License does not apply, and You do not need to comply with
160 | its terms and conditions.
161 |
162 | 3. Term. The term of this Public License is specified in Section
163 | 6(a).
164 |
165 | 4. Media and formats; technical modifications allowed. The
166 | Licensor authorizes You to exercise the Licensed Rights in
167 | all media and formats whether now known or hereafter created,
168 | and to make technical modifications necessary to do so. The
169 | Licensor waives and/or agrees not to assert any right or
170 | authority to forbid You from making technical modifications
171 | necessary to exercise the Licensed Rights, including
172 | technical modifications necessary to circumvent Effective
173 | Technological Measures. For purposes of this Public License,
174 | simply making modifications authorized by this Section 2(a)
175 | (4) never produces Adapted Material.
176 |
177 | 5. Downstream recipients.
178 |
179 | a. Offer from the Licensor -- Licensed Material. Every
180 | recipient of the Licensed Material automatically
181 | receives an offer from the Licensor to exercise the
182 | Licensed Rights under the terms and conditions of this
183 | Public License.
184 |
185 | b. Additional offer from the Licensor -- Adapted Material.
186 | Every recipient of Adapted Material from You
187 | automatically receives an offer from the Licensor to
188 | exercise the Licensed Rights in the Adapted Material
189 | under the conditions of the Adapter's License You apply.
190 |
191 | c. No downstream restrictions. You may not offer or impose
192 | any additional or different terms or conditions on, or
193 | apply any Effective Technological Measures to, the
194 | Licensed Material if doing so restricts exercise of the
195 | Licensed Rights by any recipient of the Licensed
196 | Material.
197 |
198 | 6. No endorsement. Nothing in this Public License constitutes or
199 | may be construed as permission to assert or imply that You
200 | are, or that Your use of the Licensed Material is, connected
201 | with, or sponsored, endorsed, or granted official status by,
202 | the Licensor or others designated to receive attribution as
203 | provided in Section 3(a)(1)(A)(i).
204 |
205 | b. Other rights.
206 |
207 | 1. Moral rights, such as the right of integrity, are not
208 | licensed under this Public License, nor are publicity,
209 | privacy, and/or other similar personality rights; however, to
210 | the extent possible, the Licensor waives and/or agrees not to
211 | assert any such rights held by the Licensor to the limited
212 | extent necessary to allow You to exercise the Licensed
213 | Rights, but not otherwise.
214 |
215 | 2. Patent and trademark rights are not licensed under this
216 | Public License.
217 |
218 | 3. To the extent possible, the Licensor waives any right to
219 | collect royalties from You for the exercise of the Licensed
220 | Rights, whether directly or through a collecting society
221 | under any voluntary or waivable statutory or compulsory
222 | licensing scheme. In all other cases the Licensor expressly
223 | reserves any right to collect such royalties.
224 |
225 |
226 | Section 3 -- License Conditions.
227 |
228 | Your exercise of the Licensed Rights is expressly made subject to the
229 | following conditions.
230 |
231 | a. Attribution.
232 |
233 | 1. If You Share the Licensed Material (including in modified
234 | form), You must:
235 |
236 | a. retain the following if it is supplied by the Licensor
237 | with the Licensed Material:
238 |
239 | i. identification of the creator(s) of the Licensed
240 | Material and any others designated to receive
241 | attribution, in any reasonable manner requested by
242 | the Licensor (including by pseudonym if
243 | designated);
244 |
245 | ii. a copyright notice;
246 |
247 | iii. a notice that refers to this Public License;
248 |
249 | iv. a notice that refers to the disclaimer of
250 | warranties;
251 |
252 | v. a URI or hyperlink to the Licensed Material to the
253 | extent reasonably practicable;
254 |
255 | b. indicate if You modified the Licensed Material and
256 | retain an indication of any previous modifications; and
257 |
258 | c. indicate the Licensed Material is licensed under this
259 | Public License, and include the text of, or the URI or
260 | hyperlink to, this Public License.
261 |
262 | 2. You may satisfy the conditions in Section 3(a)(1) in any
263 | reasonable manner based on the medium, means, and context in
264 | which You Share the Licensed Material. For example, it may be
265 | reasonable to satisfy the conditions by providing a URI or
266 | hyperlink to a resource that includes the required
267 | information.
268 |
269 | 3. If requested by the Licensor, You must remove any of the
270 | information required by Section 3(a)(1)(A) to the extent
271 | reasonably practicable.
272 |
273 | b. ShareAlike.
274 |
275 | In addition to the conditions in Section 3(a), if You Share
276 | Adapted Material You produce, the following conditions also apply.
277 |
278 | 1. The Adapter's License You apply must be a Creative Commons
279 | license with the same License Elements, this version or
280 | later, or a BY-SA Compatible License.
281 |
282 | 2. You must include the text of, or the URI or hyperlink to, the
283 | Adapter's License You apply. You may satisfy this condition
284 | in any reasonable manner based on the medium, means, and
285 | context in which You Share Adapted Material.
286 |
287 | 3. You may not offer or impose any additional or different terms
288 | or conditions on, or apply any Effective Technological
289 | Measures to, Adapted Material that restrict exercise of the
290 | rights granted under the Adapter's License You apply.
291 |
292 |
293 | Section 4 -- Sui Generis Database Rights.
294 |
295 | Where the Licensed Rights include Sui Generis Database Rights that
296 | apply to Your use of the Licensed Material:
297 |
298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
299 | to extract, reuse, reproduce, and Share all or a substantial
300 | portion of the contents of the database;
301 |
302 | b. if You include all or a substantial portion of the database
303 | contents in a database in which You have Sui Generis Database
304 | Rights, then the database in which You have Sui Generis Database
305 | Rights (but not its individual contents) is Adapted Material,
306 |
307 | including for purposes of Section 3(b); and
308 | c. You must comply with the conditions in Section 3(a) if You Share
309 | all or a substantial portion of the contents of the database.
310 |
311 | For the avoidance of doubt, this Section 4 supplements and does not
312 | replace Your obligations under this Public License where the Licensed
313 | Rights include other Copyright and Similar Rights.
314 |
315 |
316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
317 |
318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
328 |
329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
338 |
339 | c. The disclaimer of warranties and limitation of liability provided
340 | above shall be interpreted in a manner that, to the extent
341 | possible, most closely approximates an absolute disclaimer and
342 | waiver of all liability.
343 |
344 |
345 | Section 6 -- Term and Termination.
346 |
347 | a. This Public License applies for the term of the Copyright and
348 | Similar Rights licensed here. However, if You fail to comply with
349 | this Public License, then Your rights under this Public License
350 | terminate automatically.
351 |
352 | b. Where Your right to use the Licensed Material has terminated under
353 | Section 6(a), it reinstates:
354 |
355 | 1. automatically as of the date the violation is cured, provided
356 | it is cured within 30 days of Your discovery of the
357 | violation; or
358 |
359 | 2. upon express reinstatement by the Licensor.
360 |
361 | For the avoidance of doubt, this Section 6(b) does not affect any
362 | right the Licensor may have to seek remedies for Your violations
363 | of this Public License.
364 |
365 | c. For the avoidance of doubt, the Licensor may also offer the
366 | Licensed Material under separate terms or conditions or stop
367 | distributing the Licensed Material at any time; however, doing so
368 | will not terminate this Public License.
369 |
370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
371 | License.
372 |
373 |
374 | Section 7 -- Other Terms and Conditions.
375 |
376 | a. The Licensor shall not be bound by any additional or different
377 | terms or conditions communicated by You unless expressly agreed.
378 |
379 | b. Any arrangements, understandings, or agreements regarding the
380 | Licensed Material not stated herein are separate from and
381 | independent of the terms and conditions of this Public License.
382 |
383 |
384 | Section 8 -- Interpretation.
385 |
386 | a. For the avoidance of doubt, this Public License does not, and
387 | shall not be interpreted to, reduce, limit, restrict, or impose
388 | conditions on any use of the Licensed Material that could lawfully
389 | be made without permission under this Public License.
390 |
391 | b. To the extent possible, if any provision of this Public License is
392 | deemed unenforceable, it shall be automatically reformed to the
393 | minimum extent necessary to make it enforceable. If the provision
394 | cannot be reformed, it shall be severed from this Public License
395 | without affecting the enforceability of the remaining terms and
396 | conditions.
397 |
398 | c. No term or condition of this Public License will be waived and no
399 | failure to comply consented to unless expressly agreed to by the
400 | Licensor.
401 |
402 | d. Nothing in this Public License constitutes or may be interpreted
403 | as a limitation upon, or waiver of, any privileges and immunities
404 | that apply to the Licensor or You, including from the legal
405 | processes of any jurisdiction or authority.
406 |
407 |
408 | =======================================================================
409 |
410 | Creative Commons is not a party to its public
411 | licenses. Notwithstanding, Creative Commons may elect to apply one of
412 | its public licenses to material it publishes and in those instances
413 | will be considered the “Licensor.” The text of the Creative Commons
414 | public licenses is dedicated to the public domain under the CC0 Public
415 | Domain Dedication. Except for the limited purpose of indicating that
416 | material is shared under a Creative Commons public license or as
417 | otherwise permitted by the Creative Commons policies published at
418 | creativecommons.org/policies, Creative Commons does not authorize the
419 | use of the trademark "Creative Commons" or any other trademark or logo
420 | of Creative Commons without its prior written consent including,
421 | without limitation, in connection with any unauthorized modifications
422 | to any of its public licenses or any other arrangements,
423 | understandings, or agreements concerning use of licensed material. For
424 | the avoidance of doubt, this paragraph does not form part of the
425 | public licenses.
426 |
427 | Creative Commons may be contacted at creativecommons.org.
428 |
429 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # python wrap
4 |
5 | Demonstration, comparison and inter-operation of different c++11 class python wrapping methods, like swig, pybind11, boost-python, cython, cppyy, etc, with CMake and python `setuptools` integration example.
6 |
7 | Demonstration of mixed C++ and Python debugging will come soon.
8 |
9 | Some other similar comparison:
10 |
11 | ## Feature
12 |
13 | + demonstrate and comparr of different language binding methods
14 | + demonstrate how to build wrap code and link shared object, instead of compile all from sources
15 | + build systems: `cmake`, python `setup.py`
16 | + support C++11 with options setup in cmake and setup.py
17 | + investigate the inter-operation of compiled modules from different methods
18 | + illustration of supporting `numpy.ndarray`
19 | + introduce the approach of automated binding code generating
20 | + mixed debugging: debug C++ wrapping code when called in Python
21 |
22 |
23 | ## Tools to wrap python code
24 |
25 | ### The list of wrapping tools
26 |
27 | Wrapping binary library is possible, if header files are available.
28 |
29 | **For C code/lib interfacing**
30 | + directly use Python C-API: `#include `
31 |
32 | + `ctypes` foreign function library/module from the python standard lib, to interface binary C library in python. see [cytpes official doc](https://docs.python.org/3/library/ctypes.html)
33 |
34 | + [cffi](): an easier and automatic approach, but support only C
35 |
36 |
37 | ** Using C++ template to simplify wrapping**
38 |
39 | - [boost.python](https://www.boost.org/doc/libs/1_70_0/libs/python/doc/html/index.html): part of boost lib, it avoid lots of boiler-plate code by c++ template technology
40 | - [`pybind11`](https://github.com/pybind/pybind11): similar but with more features than boost.python
41 | - [PyCXX](http://cxx.sourceforge.net/): long existent C++ version for C-API: ``
42 |
43 | **Automatic binding generation**
44 |
45 | - [cppyy](https://cppyy.readthedocs.io/en/latest/): LLVM JIT solution without writing any wrap code, based on `cling`, still in heavy-development.
46 | - `numba`: generous automatic binding generation without user interference, but limited to math and numpy API, i.e. it can not easily link/use with third-party API.
47 | - [PyBindGen](https://pythonhosted.org/PyBindGen/index.html): similar with cppyy, using GCC to parse C++ header and generate wrapping code.
48 | - `binder`, a tool can generate pybind11 wrapping code automatically
49 | - `boost.python` wrapping code generation:
50 |
51 | Wrap C++ code in C, as the bridge to other scripting language like python, javascript. FFI can be used to automatic wrap C API into the target languages.
52 |
53 | + google tensorflow is a good example: .
54 |
55 | + swig has a not completed branch to generate C code for C++ code,
56 |
57 |
58 |
59 | + `libclang` may help to generate C interface to C++ code.
60 |
61 | Dedicated wrapping tools mainly targeting on the specific project, but can be used in other projects
62 |
63 | + Qt5: https://wiki.qt.io/Qt_for_Python/Shiboken
64 | + GTK3 : see [architecture of object introspectin](https://wiki.gnome.org/Projects/GObjectIntrospection/Architecture), it is based on libFFI.so and typelib (API info)
65 | + VTK, etc.
66 |
67 | Other solutions
68 |
69 | + [cppyy](https://cppyy.readthedocs.io/en/latest/): LLVM JIT solution without writing wrap code, based on `cling`, still in heavy-development
70 |
71 | + [swig](http://www.swig.org): wrap C/C++ to several languages like Java, and interpreting lanugages like python, etc.
72 |
73 | + [cython3](Disclaimer: This short description to each tool is very subjective, and for no means it is a complete list. the following suggestion is highly subjective
96 |
97 |
98 |
99 | ### Tools to ease the compiling process
100 |
101 | + [cppimport]() import wrapping cpp source code as normal python module
102 | + CMake support for: SWIG, CPPYY, pybind11
103 | + python `setup.py` and `build_ext()`
104 |
105 | ### Subjective suggestion
106 |
107 | For a small project with several header files, pybind11 is recommended to write pythonic interface in a manageable way.
108 |
109 | For a project with tens of headers, writing configuration file to control binder for code generation is recommended which can automatically generate boilerplate wrapping code, .
110 |
111 |
112 | If the project has no dependency on binary library, but C++ STL. It is recommended to try `cppyy` to generate the interface without writing extra interfacing code. Currently, installation and project integration is a bit difficult.
113 |
114 | For large project like , project specific fork of binder, see is used with the specific pyOCCT project.
115 |
116 | ## Repo organization
117 |
118 | + `src` : c++ header and source files
119 |
120 | the example C++ code is adapted from Cython official document with extra c++11 feature:
121 |
122 |
123 | + `*_wrap`: has wrap code, `setup.py` and `CMakeLists.txt`
124 |
125 | + Cmake is setup for each wrap methods, with top level and subfolder `CMakelists.txt`. Python `setup.py` may be also provided in case you do not use cmake build system.
126 |
127 | + submodule
128 |
129 | `git submodule add https://github.com/pybind/pybind11.git`
130 |
131 | ### Environment
132 |
133 | Tested by python3 on Ubuntu 18.04 and python2 on Ubuntu 16.04. This repo focuses on Python3, as 2.7.x has reached the end-of-life in Jan 2020.
134 |
135 | C++11 compiler is the minimum requirement, in the future, C++17 and C++20 can be added.
136 |
137 | In order to work with cmake, DO NOT USE relative include path in cython "*.pxd" and swig `*.i` files. Setup include directories in `setup.py` or cmakelists.txt instead!
138 |
139 | On windows, by default all symbols are not exported, so *.lib will not be created, so in the toplevel cmakelists.txt
140 |
141 | ```cmake
142 | SET(WINDOWS_EXPORT_ALL_SYMBOLS ON)
143 | ```
144 |
145 | This line is added to pyd target can be linked by visual c++.
146 |
147 | ### Limitations
148 | swig has error "can not find tuple" (C++11 std::tuple class) on cmake,
149 | swig has error can not find if built by setup.py on Ubuntu 16.04
150 |
151 | SWIG and Cython generated wrap code is py2 and py3 compatible, dep on which python intepretor to run setup script
152 |
153 | ## Installation and compiling extension module
154 |
155 | ### manual wrap:
156 | Install `python.h` from package `python3-dev`on Linux ( example for Ubuntu):
157 |
158 | `sudo apt-get install -y python3-dev python3-numpy cmake g++`
159 |
160 | Manually wrapping needs a lots of boiler plate code, but it is worth of reading to understand the process of wrapping.
161 |
162 |
163 |
164 | ### cython3
165 | Install `cython3` by `sudo apt-get install -y cython3 `
166 |
167 |
168 | Cython cmake supported is provided by: https://github.com/thewtex/cython-cmake-example
169 |
170 | ### pybind11
171 |
172 | Cmake will detect system wide installation,
173 | `sudo apt-get install python3-pybind11 pybind11-dev`
174 | if not installed to system wide, detect a downloaded repo to this folder. If both are not found, CMake will prompt to install:
175 |
176 | `git submodule add https://github.com/pybind/pybind11.git`
177 |
178 | pybind11 also support `setup.py` and `cppimport`. Example `setup.py` can be adapted from: https://github.com/pybind/python_example/blob/master/setup.py
179 |
180 | ### pybind11-binder (written in C++)
181 |
182 | `binder` is a tool to generate pybind11 wrapping code automatically, but it still require user configuration. It is based on LLVM and Clang, written in C++.
183 |
184 | source code:
185 |
186 | documentation:
187 |
188 | ### pybind11 binder written in python
189 |
190 | pyocct: using his own binding generator, based on python-clangp, LGPL, OCCT 7.4
191 |
192 | https://github.com/LaughlinResearch/pyOCCT
193 |
194 | macro and class template needs special treatment.
195 |
196 | ```c++
197 | template
198 |
199 | void bind_NCollection_Sequence(py::module &mod, std::string const &name, py::module_local const &local){
200 |
201 | py::class_, NCollection_BaseSequence> cls_NCollection_Sequence(mod, name.c_str(), "Purpose: Definition of a sequence of elements indexed by an Integer in range of 1..n", local);
202 | //...
203 | ```
204 |
205 | ### `boost.python`:
206 |
207 | `sudo apt-get install libboost-python-dev` it may still built against python2.
208 |
209 | There is also a tool to generate wrapping code automatically, ?
210 |
211 |
212 |
213 | ### swig:
214 | try install the latest swig for better c++11 support `sudo apt-get install -y swig3`
215 |
216 | ```bash
217 | # first of all, build the c++ shared library
218 | g++ -fPIC -shared -c ../src/Rectangle.cpp -std=c++11 -o ../lib/libshapes.so
219 | ```
220 |
221 | `setup.py` can also build module independent of python version, once `example_wrap.cxx` (works for python 2 and python 3) has been generated by `swig -python -c++ example.i`:
222 |
223 | ```bash
224 | swig -python -c++ example.i
225 | python3 setup.py build_ext --inplace
226 | ```
227 |
228 | ```bash
229 | # generate wrapping code for python 2 and python3
230 | swig -c++ -python example.i
231 | #this is not OS nor python version portable command to build the py module
232 | # to demonstrate how python module are built by `python3 setup.py build_ext --inplace`
233 | c++ -fPIC -c example_wrap.cxx -I/usr/include/python3.6m -std=c++11
234 | c++ -shared -std=c++11 example_wrap.o -lshapes -L../build -o ../lib/shape_swig.so
235 | ```
236 |
237 | If `libshapes.so` has not been install to shared library loadable location, such as LD_LIBRARY_PATH on Linux, there will be error: `cannot open shared object file: libshapes.so` . The error can be avoided by not linking to `libshapes.so`
238 |
239 | ```bash
240 | c++ -fPIC example_wrap.cxx ../src/Rectangle.cpp -I/usr/include/python3.6m -I../src -std=c++11 -shared -o ../lib/shape_swig.so
241 | # shape_swig.so is a python module, but it is wrapping of low level C API
242 | # but swig_shape.py higher level python module is generate by setup.py
243 | ```
244 |
245 | https://www.tutorialspoint.com/wrapping-c-cplusplus-for-python-using-swig
246 |
247 | CMake has official support to SWIG `swig_add_library`
248 |
249 |
250 |
251 | ### cppyy:
252 | `cppyy` is based on cling JIT intepreter, there is not compiling needed. see `test_cppyy.py`. Meanwhile, it is possible to generate importable python binding like other tools.
253 |
254 | Here is an example cmake integration in `cppyy_wrap` folder, based on
255 |
256 | > cppyy-knn: An example of cppyy-generated bindings for a simple knn implementation.
257 |
258 | https://github.com/camillescott/cppyy-knn
259 | when following this repo Readme, you need append ` -c conda-forge` to find packages. To create conda env.
260 |
261 | My experience, there is still some little work to make it more pythonic, fortunately, example can be found in this [cppyy-knn repo]( https://github.com/camillescott/cppyy-knn)
262 |
263 | http://www.camillescott.org/2019/04/11/cmake-cppyy/
264 |
265 | installation to system wide python is possible (tested on Ubuntu 18.04), it is recommended to install into conda virtualenv on linux
266 |
267 | set extra envvar by export `EXTRA_CLING_ARGS`, e.g.
268 | `export EXTRA_CLING_ARGS='-O2 -std=c++17' && python`
269 |
270 | #### pip on windows
271 |
272 | successfully `pip install cppyy` and built the wheel on window 10 with
273 |
274 | + visual studio 2019 build tool (Visual C++ compiler version 14.2)
275 |
276 | - windows 10 x64
277 | - cppyy 1.5.4
278 | - Conda python 3.7.3 (64bit) [MSC v.1915 64 bit (AMD64)]
279 |
280 | Building pre-compiled headers failed on startup for cppyy 1.5.x, it seems fix in verion 1.6.x. However, it is fine to run test with performance impact
281 |
282 | > Fatal in : fInterpreter not initialized
283 | > aborting
284 |
285 | On windows 10, only C++14 is supported, while on Linux, C++17 is supported by cppyy. check out by:
286 |
287 | ```print(cppyy.gbl.gInterpreter.ProcessLine("__cplusplus;"))```
288 |
289 | ### SIP of PyQt5 or shiboken2 for PySide2:
290 |
291 | todo:
292 |
293 | https://blog.qt.io/blog/2018/05/31/write-python-bindings/
294 |
295 | ## testing
296 |
297 | ### local test
298 |
299 | 1. `cython` seems incorporate the target shared object into python so, because source is include
300 |
301 | todo: binary
302 |
303 | 2. while pybind11 link to shared object, checked by `ldd this_python.so`
304 |
305 | 3. testing the mixed, then polymorphic code should be done
306 |
307 | https://cppyy.readthedocs.io/en/latest/classes.html
308 |
309 | ### CI matrix
310 |
311 | https://github.com/pybind/pybind11/blob/master/.travis.yml
312 |
313 |
314 |
315 | ## numpy array and Eigen Matrix interface
316 |
317 | ### pybind11
318 |
319 | #### STL vector and python buffer protocol
320 |
321 | pybind11 has built-in support for passing value of `std::vector`. To pass reference, there are two ways, make it opaque, or more generic buffer protocol by `py::buffer_info`.
322 |
323 | #### pybind11 for numpy array
324 |
325 | and numpy.array as `py::array` or restricted scallar type by `py::array_t`. `py::array_t` class, defiend in `#include `, will be automatically map into `numpy.array`. New data type for `py::array_t` can be crated by `PYBIND11_NUMPY_DTYPE(struct_name, field1, ...)`. For performance reason, index checking can be disabled by using `auto r = x.mutable_unchecked<3>()` where `x` is of type `py::array_t`
326 |
327 | see more
328 |
329 | #### pybind11 for Eigen
330 |
331 | > [Eigen](http://eigen.tuxfamily.org/) is C++ header-based library for dense and sparse linear algebra. Due to its popularity and widespread adoption, pybind11 provides transparent conversion and limited mapping support between Eigen and Scientific Python linear algebra data types.
332 |
333 | Official document has example to wrap `Eigen::MatrixXd` for numpy
334 |
335 | #### xtensor
336 |
337 | - `xtensor` is a C++14 library for multi-dimensional arrays enabling numpy-style broadcasting and lazy computing.
338 |
339 | https://xtensor.readthedocs.io/en/latest/
340 |
341 | - `xtensor-python` header-only lib enables inplace use of numpy arrays in C++ with all the benefits from `xtensor`
342 |
343 | https://github.com/xtensor-stack/xtensor-python
344 |
345 | ### cppyy
346 |
347 | `cppyy.LowLevelView` is used to convert `void*` buffer address back to numpy array `numpy.frombuffer()`, see example
348 |
349 | see
350 |
351 | passing numpy array to C++ , is surprisely hard. here is code tested to work
352 |
353 | `void* compressBlock(const unsigned char* im, std::vector shape)`
354 |
355 | ```python
356 | buf = im.tobytes() # bytes type and content is fine
357 |
358 | #pbuf = im.ctypes.data_as(ctypes.c_ubyte* len(buf))
359 | # TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_4096
360 |
361 | #pbuf = ctypes.create_string_buffer(len(buf), buf) # only for unicode string type
362 |
363 | # ctypes.POINTER(ctypes.c_ubyte) is for byte** output parameter,
364 | #pbuf = im.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte*len(buf))) # error!
365 | pbuf = array.array('B', buf) # correct
366 |
367 | # from_buffer(buf) TypeError: underlying buffer is not writable
368 | #pbuf = (ctypes.c_ubyte * len(buf)).from_buffer_copy(buf) # correctly
369 | pbuf = ctypes.cast(buf, ctypes.POINTER(ctypes.c_ubyte * len(buf)))[0] # correctly
370 |
371 | print("type of pbuf ", type(pbuf))
372 | print("content of pbuf: ", pbuf[:16])
373 |
374 | h, w = im.shape[0]//block_size, im.shape[1]//block_size
375 | arr = cppyy.gbl.compressBlock(pbuf, im.shape) # .reshape((h*w,))
376 | ```
377 |
378 |
379 |
380 | ## Compatibility and ABI
381 |
382 | ### Mixing different wrapping is possible
383 |
384 | On the python level, is it possible to use C-exnteions modules wrapped by different methods.
385 |
386 | FreeCAD project has a mixed approaches of:
387 |
388 | + swig
389 |
390 | + PyCXX, C++ wrapper of C-API in header `#include `
391 |
392 | + pybind11 may be used by some extension
393 |
394 | It is all about ABI compatibility.
395 |
396 | + C or C++ runtime ABI tends to be more stable on Linux,
397 |
398 | + Compiler like gcc has the compatible ABI since G++ 5.x.
399 |
400 | + Python 3.8 and 3.7 has different ABI, although C-API is compatible (only adding new API), there is subset API is ABI stable since 3.2, see
401 |
402 |
403 |
404 | Hint: compiling FreeCAD from source, using the same compiler as used to compile python, should work
405 |
406 | ### Passing C++ object around
407 |
408 | see discussion on Cppyy documentation section:
409 |
410 | https://cppyy.readthedocs.io/en/latest/lowlevel.html#capsules
411 |
412 | > It is not possible to pass proxies from cppyy through function arguments of another binder/wrapper (and vice versa, with the exception of `ctypes`, see below), because each will use a different internal representation, including for type checking and extracting the C++ object address. However, all Python binders are able to rebind (just like `bind_object` above for cppyy) the result of at least one of the following:
413 | >
414 | > - **ll.addressof**: Takes a cppyy bound C++ object and returns its address as an integer value. Takes an optional `byref` parameter and if set to true, returns a pointer to the address instead.
415 | > - **ll.as_capsule**: Takes a cppyy bound C++ object and returns its address as a PyCapsule object. Takes an optional `byref` parameter and if set to true, returns a pointer to the address instead.
416 | > - **ll.as_cobject**: Takes a cppyy bound C++ object and returns its address as a PyCObject object for Python2 and a PyCapsule object for Python3. Takes an optional `byref` parameter and if set to true, returns a pointer to the address instead.
417 | > - **as_ctypes**: Takes a cppyy bound C++ object and returns its address as a `ctypes.c_void_p` object. Takes an optional `byref` parameter and if set to true, returns a pointer to the address instead.
418 |
419 | ### Different C++ compilers can compile module
420 |
421 | `pybind11` wrapper cpp file can be compiled by both "mingw32-x64 v8.1" and "Visual C++ compiler version 14.2" . Python itself has compiled by one kind of compiler, usually is the platform default, such as VS studio on Windows.
422 |
423 | Python 3.8 has unified release and debug compiling ABI.
424 |
425 | Tested: Anaconda python3.7 (64bit), which has the rumtime`vcruntime140`.
426 |
427 |
428 |
429 | ## Extra readings
430 |
431 | https://intermediate-and-advanced-software-carpentry.readthedocs.io/en/latest/c++-wrapping.html
432 |
433 | [wrap binary C libriary using Cython](https://medium.com/@shamir.stav_83310/making-your-c-library-callable-from-python-by-wrapping-it-with-cython-b09db35012a3)
434 |
435 |
436 |
437 | ## License (CC BY 4.0)
438 |
439 | 
This work is licensed under a Creative Commons Attribution 4.0 International License.
440 |
441 | In short:
442 | **Share** — copy and redistribute the material in any medium or format
443 |
444 | **Adapt** — remix, transform, and build upon the material for any purpose, even commercially.
445 |
446 | **Attribution** — You must give [appropriate credit](https://creativecommons.org/licenses/by/4.0/#), provide a link to the license, and [indicate if changes were made](https://creativecommons.org/licenses/by/4.0/#). You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
447 |
448 | see license file in this repo
449 |
450 | **Note**: This CC BY 4.0 does not cover code from other projects:
451 | Cython cmake file from: https://github.com/thewtex/cython-cmake-example
452 | `boost_wrap\boost_python.cpp` which comes from stackoverflow pages, it is covered `cc by-sa 3.0`
453 |
--------------------------------------------------------------------------------
/boost_wrap/boost_python.cpp:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | tutorial from tutorial on stackoverflow
4 | user contributions licensed under cc by-sa 3.0 with attribution required.
5 | https://stackoverflow.com/questions/31555161/how-to-compile-create-shared-library-and-import-c-boost-module-in-python
6 |
7 |
8 | #sudo apt-get install python3-dev libboost-python-dev
9 | g++ -I /usr/include/python2.7 -fpic -c -o orm.o orm.cpp && g++ -o orm.so -shared orm.o -lboost_python -lpython2.7
10 | g++ -I /usr/include/python3.6 -fpic -c -o boost_wrap.o boost_wrap.cpp && g++ -o boost_wrap.so -shared boost_wrap.o -lboost_python -lpython3.6
11 |
12 | #change python2.7 to python3.6/python3.5m in both line, you should be able to compile on ubuntu 18.04
13 | */
14 |
15 | #pragma GCC diagnostic push
16 | #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
17 | #include
18 | #include
19 | #pragma GCC diagnostic pop
20 |
21 | namespace python = boost::python;
22 |
23 | class ORM
24 | {
25 | public:
26 | void foo(){std::cout << "foo" << std::endl;}
27 | };
28 |
29 | BOOST_PYTHON_MODULE(orm)
30 | {
31 | python::class_("ORM")
32 | .def("foo", &ORM::foo)
33 | ;
34 | }
--------------------------------------------------------------------------------
/cMake/FindCython.cmake:
--------------------------------------------------------------------------------
1 | # Find the Cython compiler.
2 | #
3 | # This code sets the following variables:
4 | #
5 | # CYTHON_EXECUTABLE
6 | #
7 | # See also UseCython.cmake
8 |
9 | #=============================================================================
10 | # Copyright 2011 Kitware, Inc.
11 | #
12 | # Licensed under the Apache License, Version 2.0 (the "License");
13 | # you may not use this file except in compliance with the License.
14 | # You may obtain a copy of the License at
15 | #
16 | # http://www.apache.org/licenses/LICENSE-2.0
17 | #
18 | # Unless required by applicable law or agreed to in writing, software
19 | # distributed under the License is distributed on an "AS IS" BASIS,
20 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 | # See the License for the specific language governing permissions and
22 | # limitations under the License.
23 | #=============================================================================
24 |
25 | # Use the Cython executable that lives next to the Python executable
26 | # if it is a local installation.
27 | find_package( PythonInterp )
28 | if( PYTHONINTERP_FOUND )
29 | get_filename_component( _python_path ${PYTHON_EXECUTABLE} PATH )
30 | find_program( CYTHON_EXECUTABLE
31 | NAMES cython cython.bat cython3
32 | HINTS ${_python_path}
33 | )
34 | else()
35 | find_program( CYTHON_EXECUTABLE
36 | NAMES cython cython.bat cython3
37 | )
38 | endif()
39 |
40 |
41 | include( FindPackageHandleStandardArgs )
42 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( Cython REQUIRED_VARS CYTHON_EXECUTABLE )
43 |
44 | mark_as_advanced( CYTHON_EXECUTABLE )
45 |
--------------------------------------------------------------------------------
/cMake/UseCython.cmake:
--------------------------------------------------------------------------------
1 | # Define a function to create Cython modules.
2 | #
3 | # For more information on the Cython project, see http://cython.org/.
4 | # "Cython is a language that makes writing C extensions for the Python language
5 | # as easy as Python itself."
6 | #
7 | # This file defines a CMake function to build a Cython Python module.
8 | # To use it, first include this file.
9 | #
10 | # include( UseCython )
11 | #
12 | # Then call cython_add_module to create a module.
13 | #
14 | # cython_add_module( ... )
15 | #
16 | # To create a standalone executable, the function
17 | #
18 | # cython_add_standalone_executable( [MAIN_MODULE src1] ... )
19 | #
20 | # To avoid dependence on Python, set the PYTHON_LIBRARY cache variable to point
21 | # to a static library. If a MAIN_MODULE source is specified,
22 | # the "if __name__ == '__main__':" from that module is used as the C main() method
23 | # for the executable. If MAIN_MODULE, the source with the same basename as
24 | # is assumed to be the MAIN_MODULE.
25 | #
26 | # Where is the name of the resulting Python module and
27 | # ... are source files to be compiled into the module, e.g. *.pyx,
28 | # *.py, *.c, *.cxx, etc. A CMake target is created with name . This can
29 | # be used for target_link_libraries(), etc.
30 | #
31 | # The sample paths set with the CMake include_directories() command will be used
32 | # for include directories to search for *.pxd when running the Cython complire.
33 | #
34 | # Cache variables that effect the behavior include:
35 | #
36 | # CYTHON_ANNOTATE
37 | # CYTHON_NO_DOCSTRINGS
38 | # CYTHON_FLAGS
39 | #
40 | # Source file properties that effect the build process are
41 | #
42 | # CYTHON_IS_CXX
43 | #
44 | # If this is set of a *.pyx file with CMake set_source_files_properties()
45 | # command, the file will be compiled as a C++ file.
46 | #
47 | # See also FindCython.cmake
48 |
49 | #=============================================================================
50 | # Copyright 2011 Kitware, Inc.
51 | #
52 | # Licensed under the Apache License, Version 2.0 (the "License");
53 | # you may not use this file except in compliance with the License.
54 | # You may obtain a copy of the License at
55 | #
56 | # http://www.apache.org/licenses/LICENSE-2.0
57 | #
58 | # Unless required by applicable law or agreed to in writing, software
59 | # distributed under the License is distributed on an "AS IS" BASIS,
60 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
61 | # See the License for the specific language governing permissions and
62 | # limitations under the License.
63 | #=============================================================================
64 |
65 | # Configuration options.
66 | set( CYTHON_ANNOTATE OFF
67 | CACHE BOOL "Create an annotated .html file when compiling *.pyx." )
68 | set( CYTHON_NO_DOCSTRINGS OFF
69 | CACHE BOOL "Strip docstrings from the compiled module." )
70 | set( CYTHON_FLAGS "" CACHE STRING
71 | "Extra flags to the cython compiler." )
72 | mark_as_advanced( CYTHON_ANNOTATE CYTHON_NO_DOCSTRINGS CYTHON_FLAGS )
73 |
74 | find_package( Cython REQUIRED )
75 | find_package( PythonLibs REQUIRED )
76 |
77 | set( CYTHON_CXX_EXTENSION "cxx" )
78 | set( CYTHON_C_EXTENSION "c" )
79 |
80 | # Create a *.c or *.cxx file from a *.pyx file.
81 | # Input the generated file basename. The generate file will put into the variable
82 | # placed in the "generated_file" argument. Finally all the *.py and *.pyx files.
83 | function( compile_pyx _name generated_file )
84 | # Default to assuming all files are C.
85 | set( cxx_arg "" )
86 | set( extension ${CYTHON_C_EXTENSION} )
87 | set( pyx_lang "C" )
88 | set( comment "Compiling Cython C source for ${_name}..." )
89 |
90 | set( cython_include_directories "" )
91 | set( pxd_dependencies "" )
92 | set( pxi_dependencies "" )
93 | set( c_header_dependencies "" )
94 | set( pyx_locations "" )
95 |
96 | foreach( pyx_file ${ARGN} )
97 | get_filename_component( pyx_file_basename "${pyx_file}" NAME_WE )
98 |
99 | # Determine if it is a C or C++ file.
100 | get_source_file_property( property_is_cxx ${pyx_file} CYTHON_IS_CXX )
101 | if( ${property_is_cxx} )
102 | set( cxx_arg "--cplus" )
103 | set( extension ${CYTHON_CXX_EXTENSION} )
104 | set( pyx_lang "CXX" )
105 | set( comment "Compiling Cython CXX source for ${_name}..." )
106 | endif()
107 |
108 | # Get the include directories.
109 | get_source_file_property( pyx_location ${pyx_file} LOCATION )
110 | get_filename_component( pyx_path ${pyx_location} PATH )
111 | get_directory_property( cmake_include_directories DIRECTORY ${pyx_path} INCLUDE_DIRECTORIES )
112 | list( APPEND cython_include_directories ${cmake_include_directories} )
113 | list( APPEND pyx_locations "${pyx_location}" )
114 |
115 | # Determine dependencies.
116 | # Add the pxd file will the same name as the given pyx file.
117 | unset( corresponding_pxd_file CACHE )
118 | find_file( corresponding_pxd_file ${pyx_file_basename}.pxd
119 | PATHS "${pyx_path}" ${cmake_include_directories}
120 | NO_DEFAULT_PATH )
121 | if( corresponding_pxd_file )
122 | list( APPEND pxd_dependencies "${corresponding_pxd_file}" )
123 | endif()
124 |
125 | # Look for included pxi files
126 | file(STRINGS "${pyx_file}" include_statements REGEX "include +['\"]([^'\"]+).*")
127 | foreach(statement ${include_statements})
128 | string(REGEX REPLACE "include +['\"]([^'\"]+).*" "\\1" pxi_file "${statement}")
129 | unset(pxi_location CACHE)
130 | find_file(pxi_location ${pxi_file}
131 | PATHS "${pyx_path}" ${cmake_include_directories} NO_DEFAULT_PATH)
132 | if (pxi_location)
133 | list(APPEND pxi_dependencies ${pxi_location})
134 | get_filename_component( found_pyi_file_basename "${pxi_file}" NAME_WE )
135 | get_filename_component( found_pyi_path ${pxi_location} PATH )
136 | unset( found_pyi_pxd_file CACHE )
137 | find_file( found_pyi_pxd_file ${found_pyi_file_basename}.pxd
138 | PATHS "${found_pyi_path}" ${cmake_include_directories} NO_DEFAULT_PATH )
139 | if (found_pyi_pxd_file)
140 | list( APPEND pxd_dependencies "${found_pyi_pxd_file}" )
141 | endif()
142 | endif()
143 | endforeach() # for each include statement found
144 |
145 | # pxd files to check for additional dependencies.
146 | set( pxds_to_check "${pyx_file}" "${pxd_dependencies}" )
147 | set( pxds_checked "" )
148 | set( number_pxds_to_check 1 )
149 | while( ${number_pxds_to_check} GREATER 0 )
150 | foreach( pxd ${pxds_to_check} )
151 | list( APPEND pxds_checked "${pxd}" )
152 | list( REMOVE_ITEM pxds_to_check "${pxd}" )
153 |
154 | # check for C header dependencies
155 | file( STRINGS "${pxd}" extern_from_statements
156 | REGEX "cdef[ ]+extern[ ]+from.*$" )
157 | foreach( statement ${extern_from_statements} )
158 | # Had trouble getting the quote in the regex
159 | string( REGEX REPLACE "cdef[ ]+extern[ ]+from[ ]+[\"]([^\"]+)[\"].*" "\\1" header "${statement}" )
160 | unset( header_location CACHE )
161 | find_file( header_location ${header} PATHS ${cmake_include_directories} )
162 | if( header_location )
163 | list( FIND c_header_dependencies "${header_location}" header_idx )
164 | if( ${header_idx} LESS 0 )
165 | list( APPEND c_header_dependencies "${header_location}" )
166 | endif()
167 | endif()
168 | endforeach()
169 |
170 | # check for pxd dependencies
171 |
172 | # Look for cimport statements.
173 | set( module_dependencies "" )
174 | file( STRINGS "${pxd}" cimport_statements REGEX cimport )
175 | foreach( statement ${cimport_statements} )
176 | if( ${statement} MATCHES from )
177 | string( REGEX REPLACE "from[ ]+([^ ]+).*" "\\1" module "${statement}" )
178 | else()
179 | string( REGEX REPLACE "cimport[ ]+([^ ]+).*" "\\1" module "${statement}" )
180 | endif()
181 | list( APPEND module_dependencies ${module} )
182 | endforeach()
183 | list( REMOVE_DUPLICATES module_dependencies )
184 | # Add the module to the files to check, if appropriate.
185 | foreach( module ${module_dependencies} )
186 | unset( pxd_location CACHE )
187 | find_file( pxd_location ${module}.pxd
188 | PATHS "${pyx_path}" ${cmake_include_directories} NO_DEFAULT_PATH )
189 | if( pxd_location )
190 | list( FIND pxds_checked ${pxd_location} pxd_idx )
191 | if( ${pxd_idx} LESS 0 )
192 | list( FIND pxds_to_check ${pxd_location} pxd_idx )
193 | if( ${pxd_idx} LESS 0 )
194 | list( APPEND pxds_to_check ${pxd_location} )
195 | list( APPEND pxd_dependencies ${pxd_location} )
196 | endif() # if it is not already going to be checked
197 | endif() # if it has not already been checked
198 | endif() # if pxd file can be found
199 | endforeach() # for each module dependency discovered
200 | endforeach() # for each pxd file to check
201 | list( LENGTH pxds_to_check number_pxds_to_check )
202 | endwhile()
203 |
204 |
205 |
206 | endforeach() # pyx_file
207 |
208 | # Set additional flags.
209 | if( CYTHON_ANNOTATE )
210 | set( annotate_arg "--annotate" )
211 | endif()
212 |
213 | if( CYTHON_NO_DOCSTRINGS )
214 | set( no_docstrings_arg "--no-docstrings" )
215 | endif()
216 |
217 | if( "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" OR
218 | "${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo" )
219 | set( cython_debug_arg "--gdb" )
220 | endif()
221 |
222 | if( "${PYTHONLIBS_VERSION_STRING}" MATCHES "^2." )
223 | set( version_arg "-2" )
224 | elseif( "${PYTHONLIBS_VERSION_STRING}" MATCHES "^3." )
225 | set( version_arg "-3" )
226 | else()
227 | set( version_arg )
228 | endif()
229 |
230 | # Include directory arguments.
231 | list( REMOVE_DUPLICATES cython_include_directories )
232 | set( include_directory_arg "" )
233 | foreach( _include_dir ${cython_include_directories} )
234 | set( include_directory_arg ${include_directory_arg} "-I" "${_include_dir}" )
235 | endforeach()
236 |
237 | # Determining generated file name.
238 | set( _generated_file "${CMAKE_CURRENT_BINARY_DIR}/${_name}.${extension}" )
239 | set_source_files_properties( ${_generated_file} PROPERTIES GENERATED TRUE )
240 | set( ${generated_file} ${_generated_file} PARENT_SCOPE )
241 |
242 | list( REMOVE_DUPLICATES pxd_dependencies )
243 | list( REMOVE_DUPLICATES c_header_dependencies )
244 |
245 | # Add the command to run the compiler.
246 | add_custom_command( OUTPUT ${_generated_file}
247 | COMMAND ${CYTHON_EXECUTABLE}
248 | ARGS ${cxx_arg} ${include_directory_arg} ${version_arg}
249 | ${annotate_arg} ${no_docstrings_arg} ${cython_debug_arg} ${CYTHON_FLAGS}
250 | --output-file ${_generated_file} ${pyx_locations}
251 | DEPENDS ${pyx_locations} ${pxd_dependencies} ${pxi_dependencies}
252 | IMPLICIT_DEPENDS ${pyx_lang} ${c_header_dependencies}
253 | COMMENT ${comment}
254 | )
255 |
256 | # Remove their visibility to the user.
257 | set( corresponding_pxd_file "" CACHE INTERNAL "" )
258 | set( header_location "" CACHE INTERNAL "" )
259 | set( pxd_location "" CACHE INTERNAL "" )
260 | endfunction()
261 |
262 | # cython_add_module( src1 src2 ... srcN )
263 | # Build the Cython Python module.
264 | function( cython_add_module _name )
265 | set( pyx_module_sources "" )
266 | set( other_module_sources "" )
267 | foreach( _file ${ARGN} )
268 | if( ${_file} MATCHES ".*\\.py[x]?$" )
269 | list( APPEND pyx_module_sources ${_file} )
270 | else()
271 | list( APPEND other_module_sources ${_file} )
272 | endif()
273 | endforeach()
274 | compile_pyx( ${_name} generated_file ${pyx_module_sources} )
275 | include_directories( ${PYTHON_INCLUDE_DIRS} )
276 | python_add_module( ${_name} ${generated_file} ${other_module_sources} )
277 | if( APPLE )
278 | set_target_properties( ${_name} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" )
279 | else()
280 | target_link_libraries( ${_name} ${PYTHON_LIBRARIES} )
281 | endif()
282 | endfunction()
283 |
284 | include( CMakeParseArguments )
285 | # cython_add_standalone_executable( _name [MAIN_MODULE src3.py] src1 src2 ... srcN )
286 | # Creates a standalone executable the given sources.
287 | function( cython_add_standalone_executable _name )
288 | set( pyx_module_sources "" )
289 | set( other_module_sources "" )
290 | set( main_module "" )
291 | cmake_parse_arguments( cython_arguments "" "MAIN_MODULE" "" ${ARGN} )
292 | include_directories( ${PYTHON_INCLUDE_DIRS} )
293 | foreach( _file ${cython_arguments_UNPARSED_ARGUMENTS} )
294 | if( ${_file} MATCHES ".*\\.py[x]?$" )
295 | get_filename_component( _file_we ${_file} NAME_WE )
296 | if( "${_file_we}" STREQUAL "${_name}" )
297 | set( main_module "${_file}" )
298 | elseif( NOT "${_file}" STREQUAL "${cython_arguments_MAIN_MODULE}" )
299 | set( PYTHON_MODULE_${_file_we}_static_BUILD_SHARED OFF )
300 | compile_pyx( "${_file_we}_static" generated_file "${_file}" )
301 | list( APPEND pyx_module_sources "${generated_file}" )
302 | endif()
303 | else()
304 | list( APPEND other_module_sources ${_file} )
305 | endif()
306 | endforeach()
307 |
308 | if( cython_arguments_MAIN_MODULE )
309 | set( main_module ${cython_arguments_MAIN_MODULE} )
310 | endif()
311 | if( NOT main_module )
312 | message( FATAL_ERROR "main module not found." )
313 | endif()
314 | get_filename_component( main_module_we "${main_module}" NAME_WE )
315 | set( CYTHON_FLAGS ${CYTHON_FLAGS} --embed )
316 | compile_pyx( "${main_module_we}_static" generated_file ${main_module} )
317 | add_executable( ${_name} ${generated_file} ${pyx_module_sources} ${other_module_sources} )
318 | target_link_libraries( ${_name} ${PYTHON_LIBRARIES} ${pyx_module_libs} )
319 | endfunction()
320 |
--------------------------------------------------------------------------------
/cppyy_wrap/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.10)
2 |
3 | project(cppyy_example LANGUAGES CXX)
4 |
5 | #FindLibClang.cmake
6 | #if(WIN32)
7 | #find_library(LibClang_LIBRARY libclang.dll
8 | # PATH_SUFFIXES $ENV{CONDA_PREFIX}/Library/bin
9 | #)
10 | #endif()
11 |
12 |
13 | #conda install -c conda-forge LibClang
14 | #python wrap of clang, you need to install libclang first
15 | #pip install clang # python binding clang6
16 | #install llvm6 from official and add to user PATH
17 |
18 |
19 | execute_process(COMMAND cling-config --cmake OUTPUT_VARIABLE CPPYY_MODULE_PATH OUTPUT_STRIP_TRAILING_WHITESPACE)
20 | # Make sure this is set to something like:
21 | # ~/.local/lib/python2.7/site-packages/cpyy_backend/cmake
22 | #D:\Software\Anaconda3\Lib\site-packages\cppyy_backend\cmake
23 |
24 | message("CPPYY_MODULE_PATH: " ${CPPYY_MODULE_PATH})
25 | list(INSERT CMAKE_MODULE_PATH 0 ${CPPYY_MODULE_PATH})
26 |
27 | find_package(Cppyy) #
28 |
29 | set(SOURCES ../src/Rectangle.cpp)
30 | set(HEADERS ../src/Rectangle.h)
31 |
32 | # It seems like this library has to be shared...
33 | add_library(cppyy_example SHARED ${SOURCES})
34 | # Note this is a necessary compile flag for cppyy bindings to work.
35 | set_target_properties(cppyy_example PROPERTIES POSITION_INDEPENDENT_CODE ON)
36 | target_include_directories(cppyy_example PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
37 |
38 | #windows only has c++14 support
39 | cppyy_add_bindings(
40 | "cppyy_example" "0.0.1" "Joel" "joel@joel.com"
41 | LANGUAGE_STANDARD "14"
42 | GENERATE_OPTIONS "-D__PIC__;-Wno-macro-redefined"
43 | INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}
44 | LINK_LIBRARIES cppyy_example
45 | H_DIRS ${CMAKE_CURRENT_SOURCE_DIR}
46 | H_FILES ${HEADERS})
47 |
--------------------------------------------------------------------------------
/cppyy_wrap/test_cppyy.py:
--------------------------------------------------------------------------------
1 |
2 | """ sucessfully `pip install cppyy` and built the wheel on window 10 with
3 | vs 2019 build tool, x64, cppyy 1.5.4, conda python 3.7
4 | but failed to update cppyy by `pip install -U cppyy`
5 |
6 | `cppyy_generator` does not exist, copy `cppyy_generator.exe` into cppyy_generator
7 |
8 | building pre-compiled headers failed on startup, it is fine to run with performance impact
9 | # cmake .. && MSBuild.exe SOLUTION_FILE.vcxproj
10 |
11 | #export EXTRA_CLING_ARGS='-mavx' && python
12 |
13 | """
14 |
15 | import os
16 | import os.path
17 | import cppyy
18 | #std = cppyy.gbl.std
19 | from cppyy.gbl import std
20 |
21 | # which compiler it use? cling?
22 | #print(cppyy.gbl.gInterpreter)
23 | print(cppyy.gbl.gInterpreter.ProcessLine("__cplusplus;"))
24 | #export EXTRA_CLING_ARGS='-O2 -std=c++17'
25 | #windows set to C++14
26 | ###################
27 |
28 | #cppyy.include() # header files
29 | #cppyy.load_library() # shared lib
30 | G=cppyy.gbl
31 | print("std namespace", G.std)
32 | ##########################
33 | cppyy.cppdef("""
34 | class MyClass {
35 | public:
36 | MyClass(int i) : m_data(i) {}
37 | virtual ~MyClass() {}
38 | virtual int add_int(int i) { return m_data + i; }
39 | int m_data;
40 | };""")
41 |
42 | from cppyy.gbl import MyClass
43 | m = MyClass(42)
44 | cppyy.cppdef("""
45 | void say_hello(MyClass* m) {
46 | std::cout << "Hello, the number is: " << m->m_data << std::endl;
47 | }""")
48 |
49 | MyClass.say_hello = cppyy.gbl.say_hello
50 | m.say_hello()
51 |
52 | m.m_data = 13
53 | m.say_hello()
--------------------------------------------------------------------------------
/cython_wrap/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #In your CMake configuration, make sure that PYTHON_LIBRARY, PYTHON_INCLUDE_DIR, and CYTHON_EXECUTABLE are all using the same CPython version.
2 |
3 | find_package( PythonLibs REQUIRED )
4 |
5 |
6 | if( CYTHON_EXECUTABLE )
7 | # customed cmake module downloaded from
8 | #https://github.com/thewtex/cython-cmake-example/cmake/
9 | find_package( Cython REQUIRED )
10 | include( UseCython )
11 |
12 | include_directories("${PROJECT_SOURCE_DIR}/src")
13 |
14 | # If the pyx file is a C++ file, we should specify that here.
15 | set_source_files_properties("shapes_cython.pyx"
16 | PROPERTIES CYTHON_IS_CXX TRUE )
17 |
18 | # copy the source folder, because the generated wrapping code using relative path include
19 | #file(COPY "${PROJECT_SOURCE_DIR}/src/Rectangle.cpp" DESTINATION "${PROJECT_BINARY_DIR}/src/Rectangle.cpp")
20 |
21 | # Multi-file cython modules do not appear to be working at the moment.
22 | cython_add_module( "${MY_MODULE}_cython" shapes_cython.pyx
23 | )
24 | #${PROJECT_SOURCE_DIR}/src/Rectangle.cpp
25 | link_libraries("${MY_MODULE}_cython" PRIVATE ${MY_SHARED_LIB})
26 | else()
27 | message("UseCython is not found/usable, run setup.py later")
28 | if(OFF)
29 | # the shared_object is not ready to be linked
30 | execute_process(COMMAND python3 setup.py --dist-dir ${PROJECT_BINARY_DIR} build_ext --inplace
31 | WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
32 | ERROR_VARIABLE error_var
33 | RESULT_VARIABLE ret_var)
34 | message("rv='${ret_var}'\n error msg = '${error_var}'")
35 | # copy target to a central place for testing
36 | file(COPY "*.${PY_EXTENSION}" DESTINATION "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
37 | endif()
38 | endif()
--------------------------------------------------------------------------------
/cython_wrap/Rectangle.pxd:
--------------------------------------------------------------------------------
1 | cdef extern from "Rectangle.cpp":
2 | pass
3 |
4 | # Declare the class with cdef
5 | cdef extern from "Rectangle.h" namespace "shapes":
6 | cdef cppclass Rectangle:
7 | Rectangle() except +
8 | Rectangle(int, int, int, int) except +
9 | int x0, y0, x1, y1
10 | int getArea()
11 | void getSize(int* width, int* height)
12 | void move(int, int)
--------------------------------------------------------------------------------
/cython_wrap/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 | from distutils.extension import Extension
3 | from Cython.Build import cythonize
4 |
5 | # WARNING: the library_dirs is fixed to a specific lib folder
6 | shapes_extension = Extension(
7 | name="shapes_cython",
8 | sources=["shapes_cython.pyx"],
9 | libraries=["shapes"],
10 | library_dirs=["../lib/"],
11 | include_dirs=["../src"],
12 | extra_compile_args=["-std=c++11"]
13 | )
14 |
15 | setup(
16 | name="shapes_cython",
17 | ext_modules=cythonize([shapes_extension])
18 | )
--------------------------------------------------------------------------------
/cython_wrap/shapes_cython.pyx:
--------------------------------------------------------------------------------
1 | # distutils: language = c++
2 |
3 | #Most of the containers of the C++ STL have been declared in pxd files located in /Cython/Includes/libcpp.
4 | from Rectangle cimport Rectangle
5 |
6 | # wrapping class, manually written
7 | cdef class PyRectangle:
8 | cdef Rectangle c_rect
9 |
10 | def __cinit__(self, int x0, int y0, int x1, int y1):
11 | self.c_rect = Rectangle(x0, y0, x1, y1)
12 |
13 | def getArea(self):
14 | return self.c_rect.getArea()
15 |
16 | def getSize(self):
17 | cdef int width, height
18 | self.c_rect.getSize(&width, &height)
19 | return width, height
20 |
21 | def move(self, dx, dy):
22 | self.c_rect.move(dx, dy)
23 |
24 | """
25 | # is there any friend class, to access private variable?
26 | # Attribute access
27 | @property
28 | def x0(self):
29 | return self.c_rect.x0
30 | @x0.setter
31 | def x0(self, x0):
32 | self.c_rect.x0 = x0
33 |
34 | # Attribute access
35 | @property
36 | def x1(self):
37 | return self.c_rect.x1
38 | @x1.setter
39 | def x1(self, x1):
40 | self.c_rect.x1 = x1
41 |
42 | # Attribute access
43 | @property
44 | def y0(self):
45 | return self.c_rect.y0
46 | @y0.setter
47 | def y0(self, y0):
48 | self.c_rect.y0 = y0
49 |
50 | # Attribute access
51 | @property
52 | def y1(self):
53 | return self.c_rect.y1
54 | @y1.setter
55 | def y1(self, y1):
56 | self.c_rect.y1 = y1
57 | """
--------------------------------------------------------------------------------
/pybind11_wrap/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #
2 | # copyright Qingfeng Xia 2019
3 | # CC BY 4.0
4 | #
5 |
6 | ######################################
7 | # pybind11 wrap
8 | ######################################
9 |
10 | #first of all detect system installation, then check local folder,
11 | #find_package(pybind11)
12 | if(pybind11_FOUND)
13 | message("system wide pybind11 installation found\n")
14 | # systemwide installation by package manager with header in `/usr/include/`
15 | else()
16 | if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/pybind11/include/")
17 | message("===============================================================\n"
18 | "pybind11 not found on system and ${CMAKE_CURRENT_SOURCE_DIR}, run git submodule add\n"
19 | "===============================================================\n")
20 | execute_process(COMMAND git submodule add --force https://github.com/pybind/pybind11.git
21 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
22 | ERROR_VARIABLE error_var
23 | RESULT_VARIABLE ret_var)
24 | message("rv='${ret_var}'\n error msg = '${error_var}'")
25 | # need build
26 |
27 | else()
28 | message("pybind11 is found in the folder: ${CMAKE_CURRENT_SOURCE_DIR}\n")
29 | endif()
30 |
31 | add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/pybind11")
32 | SET(pybind11_FOUND TRUE)
33 | endif()
34 |
35 |
36 | if(pybind11_FOUND)
37 | # this will generate multiple versions of py module
38 | #set(PYBIND11_PYTHON_VERSION 2.7 3.6)
39 | pybind11_add_module(${MY_MODULE}_pybind11 shapes_pybind11.cpp)
40 |
41 | # "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${MY_SHARED_LIB}"
42 | target_link_libraries(${MY_MODULE}_pybind11 PRIVATE ${MY_SHARED_LIB})
43 | else() # compile local download pybind11 lib and extra cmake module
44 | message("===============================================================\n"
45 | "pybind11 not found, please install systemwide or clone to this folder\n"
46 | "===============================================================\n")
47 | endif()
48 |
--------------------------------------------------------------------------------
/pybind11_wrap/setup.py:
--------------------------------------------------------------------------------
1 |
2 | # this file coming from https://github.com/pybind/python_example
3 | # to build the shared library, python3 setup.py build_ext
4 | # this setup.py is complete and tested
5 |
6 | from setuptools import setup, Extension
7 | from setuptools.command.build_ext import build_ext
8 | import sys
9 | import setuptools
10 |
11 | __version__ = '0.0.1'
12 |
13 |
14 | class get_pybind_include(object):
15 | """Helper class to determine the pybind11 include path
16 |
17 | The purpose of this class is to postpone importing pybind11
18 | until it is actually installed, so that the ``get_include()``
19 | method can be invoked. """
20 |
21 | def __init__(self, user=False):
22 | self.user = user
23 |
24 | def __str__(self):
25 | import pybind11
26 | return pybind11.get_include(self.user)
27 |
28 |
29 | ext_modules = [
30 | Extension(
31 | 'python_example',
32 | ['shapes_pybind11.cpp', "../src/Rectangle.cpp"],
33 | include_dirs=[
34 | # Path to pybind11 headers
35 | get_pybind_include(),
36 | get_pybind_include(user=True)
37 | ],
38 | language='c++'
39 | ),
40 | ]
41 |
42 |
43 | # As of Python 3.6, CCompiler has a `has_flag` method.
44 | # cf http://bugs.python.org/issue26689
45 | def has_flag(compiler, flagname):
46 | """Return a boolean indicating whether a flag name is supported on
47 | the specified compiler.
48 | """
49 | import tempfile
50 | with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
51 | f.write('int main (int argc, char **argv) { return 0; }')
52 | try:
53 | compiler.compile([f.name], extra_postargs=[flagname])
54 | except setuptools.distutils.errors.CompileError:
55 | return False
56 | return True
57 |
58 |
59 | def cpp_flag(compiler):
60 | """Return the -std=c++[11/14/17] compiler flag.
61 |
62 | The newer version is prefered over c++11 (when it is available).
63 | """
64 | flags = ['-std=c++17', '-std=c++14', '-std=c++11']
65 |
66 | for flag in flags:
67 | if has_flag(compiler, flag): return flag
68 |
69 | raise RuntimeError('Unsupported compiler -- at least C++11 support '
70 | 'is needed!')
71 |
72 |
73 | class BuildExt(build_ext):
74 | """A custom build extension for adding compiler-specific options."""
75 | c_opts = {
76 | 'msvc': ['/EHsc'],
77 | 'unix': [ "-g"], # debug mode, otherwise, "-O2"
78 | }
79 | l_opts = {
80 | 'msvc': [],
81 | 'unix': [],
82 | }
83 |
84 | if sys.platform == 'darwin':
85 | darwin_opts = ['-stdlib=libc++', '-mmacosx-version-min=10.7']
86 | c_opts['unix'] += darwin_opts
87 | l_opts['unix'] += darwin_opts
88 |
89 | def build_extensions(self):
90 | ct = self.compiler.compiler_type
91 | opts = self.c_opts.get(ct, [])
92 | link_opts = self.l_opts.get(ct, [])
93 | if ct == 'unix':
94 | opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version())
95 | opts.append(cpp_flag(self.compiler))
96 | if has_flag(self.compiler, '-fvisibility=hidden'):
97 | opts.append('-fvisibility=hidden')
98 | elif ct == 'msvc':
99 | opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version())
100 | for ext in self.extensions:
101 | ext.extra_compile_args = opts
102 | ext.extra_link_args = link_opts
103 | build_ext.build_extensions(self)
104 |
105 | setup(
106 | name='python_example',
107 | version=__version__,
108 | author='Sylvain Corlay',
109 | author_email='sylvain.corlay@gmail.com',
110 | url='https://github.com/pybind/python_example',
111 | description='A test project using pybind11',
112 | long_description='',
113 | ext_modules=ext_modules,
114 | install_requires=['pybind11>=2.3'],
115 | setup_requires=['pybind11>=2.3'],
116 | cmdclass={'build_ext': BuildExt},
117 | zip_safe=False,
118 | )
119 |
--------------------------------------------------------------------------------
/pybind11_wrap/shapes_pybind11.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | copyright Qingfeng Xia 2019
3 | CC BY 4.0
4 | */
5 |
6 |
7 | #include
8 | #include "../src/Rectangle.h"
9 | #include
10 |
11 | namespace py = pybind11;
12 | using namespace shapes;
13 |
14 | PYBIND11_MODULE(shapes_pybind11, m) {
15 | py::class_(m, "Rectangle")
16 | .def(py::init<>())
17 | .def(py::init())
18 | .def("getArea", &Rectangle::getArea)
19 | .def("getSize", &Rectangle::getSize)
20 | .def("getStartPoint", &Rectangle::getStartPoint)
21 | .def("move", &Rectangle::move)
22 | .def("__repr__", [](const Rectangle& r)
23 | {
24 | return "Rectangle(" + std::to_string(r.getArea()) + ")";
25 | }
26 | );
27 | }
28 |
--------------------------------------------------------------------------------
/src/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #
2 | # copyright Qingfeng Xia 2019
3 | # CC BY 4.0
4 | #
5 |
6 | #Generate the shared library from the library sources
7 | add_library(${MY_SHARED_LIB} SHARED
8 | Rectangle.cpp
9 | )
10 | #global var CMAKE_LIBRARY_OUTPUT_DIRECTORY has been set in toplevel
--------------------------------------------------------------------------------
/src/Rectangle.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | copyright Qingfeng Xia 2019
3 | CC BY 4.0
4 | */
5 |
6 | #include
7 | #include "Rectangle.h"
8 |
9 | namespace shapes {
10 |
11 | // Default constructor
12 | Rectangle::Rectangle () {}
13 |
14 | // Overloaded constructor
15 | Rectangle::Rectangle (scalar x0, scalar y0, scalar x1, scalar y1) {
16 | this->x0 = x0;
17 | this->y0 = y0;
18 | this->x1 = x1;
19 | this->y1 = y1;
20 | }
21 |
22 | // Destructor
23 | Rectangle::~Rectangle () {}
24 |
25 | std::tuple Rectangle::getStartPoint() const {
26 | return std::make_tuple(this->x0, this->y0);
27 | }
28 |
29 | // Return the area of the rectangle
30 | scalar Rectangle::getArea () const {
31 | return (this->x1 - this->x0) * (this->y1 - this->y0);
32 | }
33 |
34 | // Get the size of the rectangle.
35 | // Put the size in the pointer args
36 | void Rectangle::getSize (scalar *width, scalar *height) const{
37 | (*width) = x1 - x0;
38 | (*height) = y1 - y0;
39 | }
40 |
41 | // Move the rectangle by dx dy
42 | void Rectangle::move (scalar dx, scalar dy) {
43 | this->x0 += dx;
44 | this->y0 += dy;
45 | this->x1 += dx;
46 | this->y1 += dy;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Rectangle.h:
--------------------------------------------------------------------------------
1 | /**
2 | copyright Qingfeng Xia 2019
3 | CC BY 4.0
4 | */
5 |
6 |
7 | #ifndef RECTANGLE_H
8 | #define RECTANGLE_H
9 |
10 | #include
11 |
12 | //extern C export
13 |
14 | namespace shapes {
15 | typedef int scalar;
16 | class Rectangle {
17 | public:
18 | scalar x0, y0, x1, y1; // cython wrap code stop var to be private
19 | Rectangle();
20 | Rectangle(scalar x0, scalar y0, scalar x1, scalar y1);
21 | ~Rectangle();
22 | scalar getArea() const;
23 | void getSize(scalar* width, scalar* height) const;
24 | std::tuple getStartPoint() const ;
25 | void move(scalar dx, scalar dy);
26 | };
27 | }
28 |
29 | #endif
--------------------------------------------------------------------------------
/swig_wrap/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #
2 | # copyright Qingfeng Xia 2019
3 | # CC BY 4.0
4 | #
5 |
6 | #to use this: change the source file name for your project
7 |
8 | ######################################
9 | # setup has been done in project level, just do it again
10 | ######################################
11 |
12 | find_package(PythonInterp REQUIRED)
13 | message(STATUS "Found Python: ${PYTHON_EXECUTABLE} (found version \"${PYTHON_VERSION_STRING}\")")
14 |
15 | # cross OS setup
16 | IF(WIN32)
17 | # windows
18 | SET(PY_EXTENSION "pyd")
19 | ELSE()
20 | SET(PY_EXTENSION "so")
21 | ENDIF()
22 |
23 | # DO NOT use relative include path within *.i file, but add the include_path
24 | include_directories("${PROJECT_SOURCE_DIR}/src")
25 |
26 | ######################################
27 | # swig build
28 | ######################################
29 | message( "if this cmake failed, turn off SWIG option in cmake, and then build with setup.py")
30 | set(MY_SWIG_INTERFACE "example.i")
31 |
32 | FIND_PACKAGE(PythonLibs)
33 | INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
34 | find_package(SWIG REQUIRED) # cmake 3 has official swig support
35 | if(${CMAKE_VERSION} VERSION_GREATER "3.6.0")
36 | include(UseSWIG)
37 |
38 | set_property(SOURCE ${MY_SWIG_INTERFACE} PROPERTIES SWIG_FLAGS "-includeall")
39 | set_property(SOURCE ${MY_SWIG_INTERFACE} PROPERTY CPLUSPLUS ON)
40 |
41 | #TYPE default to MODULE
42 | swig_add_library(${MY_MODULE}_swig
43 | LANGUAGE python
44 | #NO_PROXY
45 | OUTPUT_DIR ${PROJECT_BINARY_DIR}
46 | #OUTFILE_DIR ${PROJECT_BINARY_DIR}/lib
47 | SOURCES ${MY_SWIG_INTERFACE}
48 | )
49 | else()
50 | INCLUDE(${SWIG_USE_FILE}) # 3.6 or less
51 | #http://www.swig.org/Doc3.0/SWIGDocumentation.html#Introduction_build_system
52 | SET_SOURCE_FILES_PROPERTIES( ${MY_SWIG_INTERFACE} PROPERTIES CPLUSPLUS ON)
53 | SET_SOURCE_FILES_PROPERTIES( ${MY_SWIG_INTERFACE} PROPERTIES SWIG_FLAGS "-includeall")
54 |
55 | swig_add_module("${MY_MODULE}_swig"
56 | python
57 | ${MY_SWIG_INTERFACE}
58 | )
59 | endif()
60 | #target_link_libraries, these names are defined in project cmakelists.txt
61 | swig_link_libraries(${MY_MODULE}_swig ${MY_SHARED_LIB} ${PYTHON_LIBRARIES})
62 | # the output wrap module are put into ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}
63 |
--------------------------------------------------------------------------------
/swig_wrap/example.i:
--------------------------------------------------------------------------------
1 | %module shapes_swig
2 | %{
3 | // relative include path can cause error in cmake,
4 | // in that case, add the cpp source folder into include_directories()
5 | #include "Rectangle.h"
6 | %}
7 |
8 | // cmake failed because it can not find `tuple`, while python3 setup.py is working
9 | // the following copy and paste can be avoided by %include directive
10 | //%include "Rectangle.h"
11 | // however, if there is some modification to the headers,
12 | // then you should copy the content and trim it, e.g. remove the function returning `std::tuple`
13 |
14 | namespace shapes {
15 | typedef int scalar;
16 | class Rectangle {
17 | public:
18 | scalar x0, y0, x1, y1; // cython wrap code stop var to be private
19 | Rectangle();
20 | Rectangle(scalar x0, scalar y0, scalar x1, scalar y1);
21 | ~Rectangle();
22 | scalar getArea() const;
23 | void getSize(scalar* width, scalar* height) const;
24 | //std::tuple getStartPoint() const ; // cause error
25 | void move(scalar dx, scalar dy);
26 | };
27 | }
--------------------------------------------------------------------------------
/swig_wrap/setup.py:
--------------------------------------------------------------------------------
1 | #
2 | # copyright Qingfeng Xia 2019
3 | # CC BY 4.0
4 | #
5 |
6 |
7 | from distutils.core import setup, Extension
8 | import os
9 |
10 | os.system("swig -python -c++ example.i") # generate example_wrap.cxx
11 | #swig -python -c++ example.i
12 | #the generated wrap code is py2 and py3 compatible
13 |
14 | #python3 setup.py build_ext --inplace
15 |
16 | linking_shared_object = False
17 | if not linking_shared_object:
18 | example_module = Extension('_shapes_swig',
19 | sources=['example_wrap.cxx', '../src/Rectangle.cpp'], # do not link to shared obj
20 | include_dirs=["../src"],
21 | extra_compile_args=["-std=c++11"]
22 | )
23 | else:
24 | example_module = Extension('_shapes_swig',
25 | sources=['example_wrap.cxx'], # link to shared lib (cpp)
26 | libraries=["shapes"],
27 | library_dirs=["../lib/"],
28 | include_dirs=["../src"],
29 | extra_compile_args=["-std=c++11"]
30 | )
31 |
32 | setup (name = 'shapes_swig',
33 | version = '0.1',
34 | author = "SWIG Docs",
35 | description = """Simple swig example from docs""",
36 | ext_modules = [example_module],
37 | py_modules = ["_shapes_swig"],
38 | )
39 |
40 | #you may need to copy files to other place to compare with other wrap methods
--------------------------------------------------------------------------------
/test/test_shapes.py:
--------------------------------------------------------------------------------
1 | import os.path
2 | import sys
3 | currentdir = os.path.dirname(os.path.abspath(__file__))
4 | parentdir = os.path.dirname(currentdir)
5 |
6 | sys.path.insert(0,parentdir+os.path.sep + "lib")
7 |
8 |
9 | import shapes_pybind11 as pw
10 | import shapes_cython as cw
11 |
12 | dir(pw)
13 | dir(cw)
14 |
15 | def test_init():
16 | r1 = pw.Rectangle()
17 | r2 = pw.Rectangle(0, 0, 2, 4)
18 | r3 = cw.PyRectangle()
19 | r4 = cw.PyRectangle(0, 0, 2, 4)
20 |
21 |
22 | def test_getArea():
23 | r1 = pw.Rectangle(0, 0, 2, 4)
24 | r2 = cw.PyRectangle(0, 0, 2, 4)
25 | assert r1.getArea() == r2.getArea()
26 |
27 |
28 | def test_getStartPoint():
29 | r1 = pw.Rectangle(0, 1, 2, 3)
30 | assert (0, 1) == r1.getStartPoint()
31 |
32 | test_getArea()
33 | test_getStartPoint()
--------------------------------------------------------------------------------