├── .gitignore ├── README.md ├── adder.py ├── addernet_mnist.py ├── addernet_mnist_onnx.py ├── addernet_mnist_trt.py ├── addernet_mnist_v1.py ├── addernet_mnist_v2.py ├── common.py ├── figures ├── pytorch_latency.jpg └── tensorrt_latency.jpg ├── plugin ├── Adder2dPlugin.cu ├── Adder2dPlugin.h ├── Adder2dPyTrt.cpp ├── CMakeLists.txt ├── PluginUtils.cpp ├── PluginUtils.h ├── cmake │ └── CUDA_utils.cmake └── pybind11 │ ├── .appveyor.yml │ ├── .gitignore │ ├── .gitmodules │ ├── .readthedocs.yml │ ├── .travis.yml │ ├── CMakeLists.txt │ ├── CONTRIBUTING.md │ ├── ISSUE_TEMPLATE.md │ ├── LICENSE │ ├── MANIFEST.in │ ├── README.md │ ├── docs │ ├── Doxyfile │ ├── _static │ │ └── theme_overrides.css │ ├── advanced │ │ ├── cast │ │ │ ├── chrono.rst │ │ │ ├── custom.rst │ │ │ ├── eigen.rst │ │ │ ├── functional.rst │ │ │ ├── index.rst │ │ │ ├── overview.rst │ │ │ ├── stl.rst │ │ │ └── strings.rst │ │ ├── classes.rst │ │ ├── embedding.rst │ │ ├── exceptions.rst │ │ ├── functions.rst │ │ ├── misc.rst │ │ ├── pycpp │ │ │ ├── index.rst │ │ │ ├── numpy.rst │ │ │ ├── object.rst │ │ │ └── utilities.rst │ │ └── smart_ptrs.rst │ ├── basics.rst │ ├── benchmark.py │ ├── benchmark.rst │ ├── changelog.rst │ ├── classes.rst │ ├── compiling.rst │ ├── conf.py │ ├── faq.rst │ ├── index.rst │ ├── intro.rst │ ├── limitations.rst │ ├── pybind11-logo.png │ ├── pybind11_vs_boost_python1.png │ ├── pybind11_vs_boost_python1.svg │ ├── pybind11_vs_boost_python2.png │ ├── pybind11_vs_boost_python2.svg │ ├── reference.rst │ ├── release.rst │ ├── requirements.txt │ └── upgrade.rst │ ├── include │ └── pybind11 │ │ ├── attr.h │ │ ├── buffer_info.h │ │ ├── cast.h │ │ ├── chrono.h │ │ ├── common.h │ │ ├── complex.h │ │ ├── detail │ │ ├── class.h │ │ ├── common.h │ │ ├── descr.h │ │ ├── init.h │ │ ├── internals.h │ │ └── typeid.h │ │ ├── eigen.h │ │ ├── embed.h │ │ ├── eval.h │ │ ├── functional.h │ │ ├── iostream.h │ │ ├── numpy.h │ │ ├── operators.h │ │ ├── options.h │ │ ├── pybind11.h │ │ ├── pytypes.h │ │ ├── stl.h │ │ └── stl_bind.h │ ├── pybind11 │ ├── __init__.py │ ├── __main__.py │ └── _version.py │ ├── setup.cfg │ ├── setup.py │ ├── tests │ ├── CMakeLists.txt │ ├── conftest.py │ ├── constructor_stats.h │ ├── cross_module_gil_utils.cpp │ ├── local_bindings.h │ ├── object.h │ ├── pybind11_cross_module_tests.cpp │ ├── pybind11_tests.cpp │ ├── pybind11_tests.h │ ├── pytest.ini │ ├── test_async.cpp │ ├── test_async.py │ ├── test_buffers.cpp │ ├── test_buffers.py │ ├── test_builtin_casters.cpp │ ├── test_builtin_casters.py │ ├── test_call_policies.cpp │ ├── test_call_policies.py │ ├── test_callbacks.cpp │ ├── test_callbacks.py │ ├── test_chrono.cpp │ ├── test_chrono.py │ ├── test_class.cpp │ ├── test_class.py │ ├── test_cmake_build │ │ ├── CMakeLists.txt │ │ ├── embed.cpp │ │ ├── installed_embed │ │ │ └── CMakeLists.txt │ │ ├── installed_function │ │ │ └── CMakeLists.txt │ │ ├── installed_target │ │ │ └── CMakeLists.txt │ │ ├── main.cpp │ │ ├── subdirectory_embed │ │ │ └── CMakeLists.txt │ │ ├── subdirectory_function │ │ │ └── CMakeLists.txt │ │ ├── subdirectory_target │ │ │ └── CMakeLists.txt │ │ └── test.py │ ├── test_constants_and_functions.cpp │ ├── test_constants_and_functions.py │ ├── test_copy_move.cpp │ ├── test_copy_move.py │ ├── test_docstring_options.cpp │ ├── test_docstring_options.py │ ├── test_eigen.cpp │ ├── test_eigen.py │ ├── test_embed │ │ ├── CMakeLists.txt │ │ ├── catch.cpp │ │ ├── external_module.cpp │ │ ├── test_interpreter.cpp │ │ └── test_interpreter.py │ ├── test_enum.cpp │ ├── test_enum.py │ ├── test_eval.cpp │ ├── test_eval.py │ ├── test_eval_call.py │ ├── test_exceptions.cpp │ ├── test_exceptions.py │ ├── test_factory_constructors.cpp │ ├── test_factory_constructors.py │ ├── test_gil_scoped.cpp │ ├── test_gil_scoped.py │ ├── test_iostream.cpp │ ├── test_iostream.py │ ├── test_kwargs_and_defaults.cpp │ ├── test_kwargs_and_defaults.py │ ├── test_local_bindings.cpp │ ├── test_local_bindings.py │ ├── test_methods_and_attributes.cpp │ ├── test_methods_and_attributes.py │ ├── test_modules.cpp │ ├── test_modules.py │ ├── test_multiple_inheritance.cpp │ ├── test_multiple_inheritance.py │ ├── test_numpy_array.cpp │ ├── test_numpy_array.py │ ├── test_numpy_dtypes.cpp │ ├── test_numpy_dtypes.py │ ├── test_numpy_vectorize.cpp │ ├── test_numpy_vectorize.py │ ├── test_opaque_types.cpp │ ├── test_opaque_types.py │ ├── test_operator_overloading.cpp │ ├── test_operator_overloading.py │ ├── test_pickling.cpp │ ├── test_pickling.py │ ├── test_pytypes.cpp │ ├── test_pytypes.py │ ├── test_sequences_and_iterators.cpp │ ├── test_sequences_and_iterators.py │ ├── test_smart_ptr.cpp │ ├── test_smart_ptr.py │ ├── test_stl.cpp │ ├── test_stl.py │ ├── test_stl_binders.cpp │ ├── test_stl_binders.py │ ├── test_tagbased_polymorphic.cpp │ ├── test_tagbased_polymorphic.py │ ├── test_union.cpp │ ├── test_union.py │ ├── test_virtual_functions.cpp │ └── test_virtual_functions.py │ └── tools │ ├── FindCatch.cmake │ ├── FindEigen3.cmake │ ├── FindPythonLibsNew.cmake │ ├── check-style.sh │ ├── clang │ ├── .gitignore │ ├── LICENSE.TXT │ ├── README.md │ ├── __init__.py │ ├── cindex.py │ └── enumerations.py │ ├── libsize.py │ ├── mkdoc.py │ ├── pybind11Config.cmake.in │ └── pybind11Tools.cmake ├── rand_image ├── test_img.npy ├── test_img.pt ├── test_label.npy └── test_label.pt ├── saved_models ├── addernet_mnist.pth ├── addernet_mnist_v1.pth └── addernet_mnist_v2.pth └── test ├── TestAdder2dPlugin.cpp ├── TestAdderFilterCudaKernel.cu ├── test_adder2dplugin_pybind.py ├── test_adder_layer.py └── test_adder_layer_trt.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AdderNet Model Conversion to TensorRT 2 | 3 |

4 | 5 |

6 | 7 |

8 | 9 |

10 | 11 | 12 | ## Requirements 13 | - cuda 10.2 14 | - cudnn 8.0 15 | - TensorRT 7.1 16 | - python 3.6 17 | - pytorch = 1.6.0 18 | 19 | 20 | # AdderNetTensorRT 21 | This project implements the Adder Layer mentioned in https://arxiv.org/pdf/1912.13200.pdf using TensorRT custom layer Plugin API. 22 | Original pytorch implementation of the AdderNet is found in https://github.com/huawei-noah/AdderNet/. That is not CUDA or TensoRT capable. 23 | 24 | Execute the following scripts for latency and accuracy calculation. 25 | ```bash 26 | python addernet_mnist.py --> for pytorch results 27 | python addernet_mnist_trt.py --> for tensorrt results 28 | ``` 29 | 30 | Execute the following scripts for unit test the adder layer. 31 | Output feature values should be the same from both scripts. 32 | ```bash 33 | cd test 34 | python test_adder_layer.py --> for pytorch results 35 | python test_adder_layer_trt.py --> for tensorrt results 36 | ``` 37 | 38 | Any other neural network architectures containing Adder Layers can be implemented in TensorRT using this Adder Layer Plugin. 39 | 40 | addenet_mnist_v1.py is implemented without BatchNormalization layers. If you train this model you'll see the model is not training well. 41 | addenet_mnist_v2.py is also implemented without BatchNormalization layers but tanh activation is used instead of relu to get use of the negative values outputs from Adder layers. 42 | Still the model is not training well. 43 | 44 | # System Requirements 45 | - python 3.6, numpy, matplotlib 46 | - gcc 7.5.0 47 | - cuda 10.2 48 | - cudnn 8.0 49 | - TensorRT 7.1 50 | - PyTorch>=1.5 51 | 52 | # Installation 53 | Make sure you have installed the dependency list above. 54 | ```bash 55 | cd AdderNet_TensorRT/plugin 56 | mkdir build 57 | cd build 58 | cmake .. 59 | make 60 | ``` 61 | Following files will be created in the build directory. 62 | - libadder2dtrt.so shared library for cpp unit test cases in the build folder. 63 | - adder2dpytrt.so pybind library to be used when import Adder2dPlugin using python modules. 64 | - Two Unit testing executables named 'TestAdder2dPlugin' and 'TestAdderFilterCudaKernel'. 65 | 66 | -------------------------------------------------------------------------------- /adder.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | This program is free software; you can redistribute it and/or modify 4 | it under the terms of BSD 3-Clause License. 5 | This program is distributed in the hope that it will be useful, 6 | but WITHOUT ANY WARRANTY; without even the implied warranty of 7 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 8 | BSD 3-Clause License for more details. 9 | ''' 10 | import torch 11 | import torch.nn as nn 12 | import numpy as np 13 | from torch.autograd import Function 14 | import math 15 | 16 | 17 | def adder2d_function(X, W, stride=1, padding=0): 18 | n_filters, d_filter, h_filter, w_filter = W.size() 19 | n_x, d_x, h_x, w_x = X.size() 20 | 21 | h_out = (h_x - h_filter + 2 * padding) // stride + 1 22 | w_out = (w_x - w_filter + 2 * padding) // stride + 1 23 | 24 | h_out, w_out = int(h_out), int(w_out) 25 | X_col = torch.nn.functional.unfold(X.view(1, -1, h_x, w_x), int(h_filter), dilation=1, padding=padding, stride=stride).view(n_x, -1, h_out*w_out) 26 | X_col = X_col.permute(1,2,0).contiguous().view(X_col.size(1),-1) 27 | W_col = W.view(n_filters, -1) 28 | 29 | out = adder.apply(W_col,X_col) 30 | 31 | out = out.view(n_filters, h_out, w_out, n_x) 32 | out = out.permute(3, 0, 1, 2).contiguous() 33 | 34 | return out 35 | 36 | 37 | class adder(Function): 38 | @staticmethod 39 | def forward(ctx, W_col, X_col): 40 | ctx.save_for_backward(W_col,X_col) 41 | output = -(W_col.unsqueeze(2)-X_col.unsqueeze(0)).abs().sum(1) 42 | return output 43 | 44 | @staticmethod 45 | def backward(ctx,grad_output): 46 | W_col,X_col = ctx.saved_tensors 47 | grad_W_col = ((X_col.unsqueeze(0)-W_col.unsqueeze(2))*grad_output.unsqueeze(1)).sum(2) 48 | grad_W_col = grad_W_col/grad_W_col.norm(p=2).clamp(min=1e-12)*math.sqrt(W_col.size(1)*W_col.size(0))/5 49 | grad_X_col = (-(X_col.unsqueeze(0)-W_col.unsqueeze(2)).clamp(-1,1)*grad_output.unsqueeze(1)).sum(0) 50 | 51 | return grad_W_col, grad_X_col 52 | 53 | 54 | class adder2d(nn.Module): 55 | 56 | def __init__(self,input_channel,output_channel,kernel_size, stride=1, padding=0, bias = False): 57 | super(adder2d, self).__init__() 58 | self.stride = stride 59 | self.padding = padding 60 | self.input_channel = input_channel 61 | self.output_channel = output_channel 62 | self.kernel_size = kernel_size 63 | self.adder = torch.nn.Parameter(nn.init.normal_(torch.randn(output_channel,input_channel,kernel_size,kernel_size))) 64 | self.bias = bias 65 | if bias: 66 | self.b = torch.nn.Parameter(nn.init.uniform_(torch.zeros(output_channel))) 67 | 68 | def forward(self, x): 69 | output = adder2d_function(x,self.adder, self.stride, self.padding) 70 | if self.bias: 71 | output += self.b.unsqueeze(0).unsqueeze(2).unsqueeze(3) 72 | 73 | return output 74 | 75 | -------------------------------------------------------------------------------- /addernet_mnist_onnx.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import onnx 3 | 4 | from addernet_mnist import MnistModel 5 | OPSET = 12 6 | 7 | 8 | model = MnistModel() 9 | model.network.load_state_dict(torch.load('./saved_models/addernet_mnist.pth')) 10 | model.network.to('cuda') 11 | 12 | dummy_input = torch.randn(1, 1, 28, 28, device='cuda') 13 | 14 | # convert pytorch model to onnx format 15 | torch.onnx.export(model.network, dummy_input, "./saved_models/addernet_mnist.onnx", verbose=True, opset_version=OPSET) 16 | 17 | # Load the ONNX model 18 | model = onnx.load("./saved_models/addernet_mnist.onnx") 19 | # Check that the IR is well formed 20 | onnx.checker.check_model(model) 21 | # Print a human readable representation of the graph 22 | onnx.helper.printable_graph(model.graph) 23 | -------------------------------------------------------------------------------- /addernet_mnist_v1.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import torch.optim as optim 5 | from torchvision import datasets, transforms 6 | from torch.autograd import Variable 7 | from torchsummary import summary 8 | 9 | import numpy as np 10 | from random import randint 11 | 12 | import adder 13 | 14 | 15 | # Network 16 | class Net(nn.Module): 17 | def __init__(self): 18 | super(Net, self).__init__() 19 | self.adder1 = adder.adder2d(1, 20, kernel_size=5, stride=1, padding=0, bias=False) 20 | self.adder2 = adder.adder2d(20, 50, kernel_size=5, stride=1, padding=0, bias=False) 21 | self.fc1 = nn.Linear(800, 500) 22 | self.fc2 = nn.Linear(500, 10) 23 | 24 | def forward(self, x): 25 | x = F.max_pool2d(self.adder1(x), kernel_size=2, stride=2) 26 | x = F.max_pool2d(self.adder2(x), kernel_size=2, stride=2) 27 | x = x.view(-1, 800) 28 | x = F.relu(self.fc1(x)) 29 | x = self.fc2(x) 30 | return F.log_softmax(x, dim=1) 31 | 32 | 33 | class MnistModel(object): 34 | def __init__(self): 35 | self.batch_size = 64 36 | self.test_batch_size = 100 37 | self.learning_rate = 0.0025 38 | self.sgd_momentum = 0.9 39 | self.log_interval = 100 40 | # Fetch MNIST data set. 41 | self.train_loader = torch.utils.data.DataLoader( 42 | datasets.MNIST('./data/mnist', train=True, download=True, transform=transforms.Compose([ 43 | transforms.ToTensor(), 44 | transforms.Normalize((0.1307,), (0.3081,)) 45 | ])), 46 | batch_size=self.batch_size, 47 | shuffle=True) 48 | self.test_loader = torch.utils.data.DataLoader( 49 | datasets.MNIST('./data/mnist', train=False, transform=transforms.Compose([ 50 | transforms.ToTensor(), 51 | transforms.Normalize((0.1307,), (0.3081,)) 52 | ])), 53 | batch_size=self.test_batch_size, 54 | shuffle=True) 55 | self.network = Net().cpu() 56 | print(self.network) 57 | summary(self.network, (1, 28, 28), device='cpu') 58 | 59 | # Train the network for one or more epochs, validating after each epoch. 60 | def learn(self, num_epochs=2): 61 | # Train the network for a single epoch 62 | def train(epoch): 63 | self.network.train() 64 | optimizer = optim.SGD(self.network.parameters(), lr=self.learning_rate, momentum=self.sgd_momentum) 65 | for batch, (data, target) in enumerate(self.train_loader): 66 | data, target = Variable(data), Variable(target) 67 | optimizer.zero_grad() 68 | output = self.network(data) 69 | loss = F.nll_loss(output, target) 70 | loss.backward() 71 | optimizer.step() 72 | if batch % self.log_interval == 0: 73 | print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch, batch * len(data), len(self.train_loader.dataset), 100. * batch / len(self.train_loader), loss.data.item())) 74 | 75 | # Test the network 76 | def test(epoch): 77 | self.network.eval() 78 | test_loss = 0 79 | correct = 0 80 | for data, target in self.test_loader: 81 | with torch.no_grad(): 82 | data, target = Variable(data), Variable(target) 83 | output = self.network(data) 84 | test_loss += F.nll_loss(output, target).data.item() 85 | pred = output.data.max(1)[1] 86 | correct += pred.eq(target.data).cpu().sum() 87 | test_loss /= len(self.test_loader) 88 | print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(test_loss, correct, len(self.test_loader.dataset), 100. * correct / len(self.test_loader.dataset))) 89 | 90 | for e in range(num_epochs): 91 | train(e + 1) 92 | test(e + 1) 93 | 94 | def get_weights(self): 95 | return self.network.state_dict() 96 | 97 | def get_random_testcase(self): 98 | data, target = next(iter(self.test_loader)) 99 | case_num = randint(0, len(data) - 1) 100 | test_case = data.numpy()[case_num].ravel().astype(np.float32) 101 | test_name = target.numpy()[case_num] 102 | return test_case, test_name 103 | 104 | 105 | def main(): 106 | mnist_model = MnistModel() 107 | mnist_model.learn() 108 | torch.save(mnist_model.get_weights(), './saved_models/addernet_mnist_v1.pth') 109 | # weights = mnist_model.get_weights() 110 | # print(weights) 111 | 112 | 113 | if __name__ == '__main__': 114 | main() -------------------------------------------------------------------------------- /figures/pytorch_latency.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/figures/pytorch_latency.jpg -------------------------------------------------------------------------------- /figures/tensorrt_latency.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/figures/tensorrt_latency.jpg -------------------------------------------------------------------------------- /plugin/Adder2dPlugin.h: -------------------------------------------------------------------------------- 1 | #ifndef ADDER2D_PLUGIN_H 2 | #define ADDER2D_PLUGIN_H 3 | 4 | #include "NvInfer.h" 5 | #include "NvInferPlugin.h" 6 | 7 | #include 8 | 9 | class Adder2dPlugin : public nvinfer1::IPluginV2 10 | { 11 | public: 12 | Adder2dPlugin(const nvinfer1::Weights *weights, int nbWeights, int nbInputChannels, int inputHeight, 13 | int inputWidth, int filterSize, int nbFilters, int stride, int padding); 14 | 15 | Adder2dPlugin(const void *data, size_t length); 16 | 17 | ~Adder2dPlugin(); 18 | 19 | virtual int getNbOutputs() const override; 20 | 21 | virtual nvinfer1::Dims getOutputDimensions(int index, const nvinfer1::Dims* inputs, int nbInputDims) override; 22 | 23 | virtual bool supportsFormat(nvinfer1::DataType type, nvinfer1::PluginFormat format) const override; 24 | 25 | virtual void configureWithFormat(const nvinfer1::Dims* inputDims, int nbInputs, const nvinfer1::Dims* outputDims, 26 | int nbOutputs, nvinfer1::DataType type, nvinfer1::PluginFormat format, 27 | int maxBatchSize) override; 28 | 29 | virtual int initialize() override; 30 | 31 | virtual void terminate() override; 32 | 33 | virtual size_t getWorkspaceSize(int maxBatchSize) const override; 34 | 35 | virtual int enqueue(int batchSize, const void*const * inputs, void** outputs, void* workspace, cudaStream_t stream) override; 36 | 37 | virtual size_t getSerializationSize() const override; 38 | 39 | virtual void serialize(void* buffer) const override; 40 | 41 | virtual const char* getPluginType() const override; 42 | 43 | virtual const char* getPluginVersion() const override; 44 | 45 | virtual void destroy(); 46 | 47 | virtual IPluginV2* clone() const override; 48 | 49 | virtual void setPluginNamespace(const char* pluginNamespace) override; 50 | 51 | virtual const char* getPluginNamespace() const override; 52 | 53 | private: 54 | int mNbWeights, mNbInputChannels, mInputHeight, mInputWidth, mFilterSize, mNbFilters, mStride, mPadding; 55 | nvinfer1::Weights mWeights; 56 | nvinfer1::DataType mDataType{nvinfer1::DataType::kFLOAT}; 57 | void* mDeviceWeightPtr{nullptr}; 58 | }; 59 | 60 | 61 | class Adder2dPluginCreator : public nvinfer1::IPluginCreator { 62 | public: 63 | Adder2dPluginCreator(); 64 | 65 | // ------------------inherit from IPluginCreator------------------- 66 | // return the plugin type + plugin namesapce 67 | virtual const char* getPluginName() const override; 68 | 69 | // return the plugin version 70 | virtual const char* getPluginVersion() const override; 71 | 72 | // return a list of fields that needs to be passed to createPlugin 73 | virtual const nvinfer1::PluginFieldCollection* getFieldNames() override; 74 | 75 | // return nullptr in case of error 76 | virtual nvinfer1::IPluginV2* createPlugin(const char* name, const nvinfer1::PluginFieldCollection *fc) override; 77 | 78 | // Called during deserialization of plugin layer. Return a plugin object. 79 | virtual nvinfer1::IPluginV2* deserializePlugin(const char* name, const void* serialData, size_t serialLenth) override; 80 | 81 | // Set the namespace of the plugin creator based on the plugin library it belongs to. This can be set while registering the plugin creator 82 | virtual void setPluginNamespace(const char* pluginNamespace) override {} 83 | 84 | // Return the namespace of the plugin creator object. 85 | virtual const char* getPluginNamespace() const override; 86 | 87 | private: 88 | nvinfer1::PluginFieldCollection mFC; 89 | std::vector mPluginAttributes; 90 | }; 91 | 92 | 93 | #endif //ADDER2D_PLUGIN_H -------------------------------------------------------------------------------- /plugin/Adder2dPyTrt.cpp: -------------------------------------------------------------------------------- 1 | #include "Adder2dPlugin.h" 2 | 3 | #include 4 | namespace py = pybind11; 5 | 6 | PYBIND11_MODULE(adder2dpytrt, m) { 7 | py::class_(m, "Adder2dPlugin") 8 | .def(py::init(), 9 | py::arg("weights"), py::arg("nbWeights"), py::arg("nbInputChannels"), py::arg("inputHeight"), py::arg("inputWidth"), 10 | py::arg("filterSize"), py::arg("nbFilters"), py::arg("stride"), py::arg("padding")) 11 | .def(py::init(), py::arg("data"), py::arg("length")) 12 | .def("getSerializationSize", &Adder2dPlugin::getSerializationSize); 13 | } 14 | -------------------------------------------------------------------------------- /plugin/PluginUtils.cpp: -------------------------------------------------------------------------------- 1 | #include "PluginUtils.h" 2 | 3 | size_t type2size(nvinfer1::DataType type) { 4 | if(type == nvinfer1::DataType::kFLOAT) { 5 | return 4; 6 | } else if (type == nvinfer1::DataType::kHALF) { 7 | return 2; 8 | } else if (type == nvinfer1::DataType::kINT8) { 9 | return 1; 10 | } else { 11 | ASSERT(false); 12 | } 13 | } 14 | 15 | void* copyToDevice(const void* data, size_t count) { 16 | void *deviceData; 17 | CUDA_CHECK(cudaMalloc(&deviceData, count)); 18 | CUDA_CHECK(cudaMemcpy(deviceData, data, count, cudaMemcpyHostToDevice)); 19 | return deviceData; 20 | } 21 | 22 | void copyToBuffer(char*& buffer, const void* data, size_t count) { 23 | memcpy(buffer, data, count); 24 | } 25 | 26 | void convertAndCopyToDeivce(void*& deviceWeights, const nvinfer1::Weights &weights, 27 | nvinfer1::DataType datatype) { 28 | size_t size = weights.count * type2size(datatype); 29 | if (weights.type != datatype) // Weights are converted in host memory first, if the type does not match 30 | { 31 | void *buffer = malloc(size); 32 | for (int64_t v = 0; v < weights.count; ++v) 33 | if (datatype == nvinfer1::DataType::kFLOAT) 34 | static_cast(buffer)[v] = __half2float(static_cast(weights.values)[v]); 35 | else 36 | static_cast<__half *>(buffer)[v] = __float2half(static_cast(weights.values)[v]); 37 | 38 | deviceWeights = copyToDevice(buffer, size); 39 | free(buffer); 40 | } 41 | else 42 | deviceWeights = copyToDevice(weights.values, size); 43 | } 44 | 45 | void convertAndCopyToBuffer(char*& buffer, const nvinfer1::Weights weights, 46 | nvinfer1::DataType datatype) { 47 | size_t size = weights.count * type2size(datatype); 48 | if(weights.type != datatype) { 49 | for (int64_t v = 0; v < weights.count; ++v) { 50 | if (datatype == nvinfer1::DataType::kFLOAT) 51 | reinterpret_cast(buffer)[v] = __half2float(static_cast(weights.values)[v]); 52 | else 53 | reinterpret_cast<__half *>(buffer)[v] = __float2half(static_cast(weights.values)[v]); 54 | } 55 | } else { 56 | copyToBuffer(buffer, weights.values, size); 57 | } 58 | buffer += size; 59 | } 60 | -------------------------------------------------------------------------------- /plugin/PluginUtils.h: -------------------------------------------------------------------------------- 1 | #ifndef PLUGIN_UTILS_H 2 | #define PLUGIN_UTILS_H 3 | 4 | #include "NvInfer.h" 5 | #include "cuda_runtime.h" 6 | #include "cuda_fp16.h" 7 | 8 | #include 9 | #include 10 | 11 | // this is for debug, and you can find a lot assert in plugin implementation, 12 | // it will reduce the time spend on debug 13 | #define ASSERT(assertion) \ 14 | { \ 15 | if (!(assertion)) \ 16 | { \ 17 | std::cerr << "#assertion fail " << __FILE__ << " line " << __LINE__ << std::endl; \ 18 | abort(); \ 19 | } \ 20 | } 21 | 22 | #define UNUSED(unusedVariable) (void)(unusedVariable) 23 | // suppress compiler warning: unused parameter 24 | 25 | inline int64_t volume(const nvinfer1::Dims& d){ 26 | return std::accumulate(d.d, d.d + d.nbDims, 1, std::multiplies()); 27 | } 28 | 29 | inline unsigned int getElementSize(nvinfer1::DataType t){ 30 | switch (t) 31 | { 32 | case nvinfer1::DataType::kINT32: return 4; 33 | case nvinfer1::DataType::kFLOAT: return 4; 34 | case nvinfer1::DataType::kHALF: return 2; 35 | case nvinfer1::DataType::kINT8: return 1; 36 | default: throw std::runtime_error("Invalid DataType."); 37 | } 38 | } 39 | 40 | 41 | #ifndef CUDA_CHECK 42 | #define CUDA_CHECK(callstr) \ 43 | { \ 44 | cudaError_t error_code = callstr; \ 45 | if (error_code != cudaSuccess) { \ 46 | std::cerr << "CUDA error " << error_code << " at " << __FILE__ << ":" << __LINE__ << std::endl; \ 47 | exit(0); \ 48 | } \ 49 | } 50 | #endif 51 | 52 | inline void* safeCudaMalloc(size_t memSize) { 53 | void* deviceMem; 54 | CUDA_CHECK(cudaMalloc(&deviceMem, memSize)); 55 | if (deviceMem == nullptr) { 56 | std::cerr << "Out of memory" << std::endl; 57 | exit(1); 58 | } 59 | return deviceMem; 60 | } 61 | 62 | inline void safeCudaFree(void* deviceMem) { 63 | CUDA_CHECK(cudaFree(deviceMem)); 64 | } 65 | 66 | inline void error(const std::string& message, const int line, const std::string& function, const std::string& file) { 67 | std::cout << message << " at " << line << " in " << function << " in " << file << std::endl; 68 | } 69 | 70 | 71 | // write value to buffer 72 | template 73 | void write(char *&buffer, const T &val) 74 | { 75 | *reinterpret_cast(buffer) = val; 76 | buffer += sizeof(T); 77 | } 78 | 79 | // read value from buffer 80 | template 81 | void read(const char *&buffer, T &val) 82 | { 83 | val = *reinterpret_cast(buffer); 84 | buffer += sizeof(T); 85 | } 86 | 87 | 88 | 89 | // return needed space of a datatype 90 | size_t type2size(nvinfer1::DataType type); 91 | 92 | // copy data to device memory 93 | void* copyToDevice(const void* data, size_t count); 94 | 95 | // copy data to buffer. 96 | void copyToBuffer(char*& buffer, const void* data, size_t count); 97 | 98 | // convert data to datatype and copy it to device 99 | void convertAndCopyToDeivce(void*& deviceWeights, const nvinfer1::Weights &weights, 100 | nvinfer1::DataType datatype); 101 | 102 | // convert data to datatype and copy it to buffer 103 | void convertAndCopyToBuffer(char*& buffer, const nvinfer1::Weights weights, 104 | nvinfer1::DataType datatype); 105 | 106 | // deserialize buffer to device memory. 107 | void deserializeToDevice(const char*& hostBuffer, void*& deviceWeights, size_t size); 108 | 109 | #endif //PLUGIN_UTILS_H -------------------------------------------------------------------------------- /plugin/cmake/CUDA_utils.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | # List of currently used arch values 17 | set(CUDA_known_archs "60" "61" "70" "75") 18 | 19 | set(CUDA_TARGET_ARCHS ${CUDA_known_archs} CACHE STRING "List of target CUDA architectures") 20 | if ("${CUDA_TARGET_ARCHS}" STREQUAL "") 21 | message("CUDA_TARGET_ARCHS cannot be empty, setting to the default") 22 | set(CUDA_TARGET_ARCHS ${CUDA_known_archs} CACHE STRING "List of target CUDA architectures" FORCE) 23 | endif() 24 | 25 | # Find if passing `flags` to nvcc producess success or failure 26 | # Unix only 27 | # 28 | # Equivalent to dry-running preprocessing on /dev/null as .cu file 29 | # and checking the exit code 30 | # $ nvcc ${flags} --dryrun -E -x cu /dev/null 31 | # 32 | # @param out_status TRUE iff exit code is 0, FALSE otherwise 33 | # @param nvcc_bin nvcc binary to use in shell invocation 34 | # @param flags flags to check 35 | # @return out_status 36 | function(CUDA_check_nvcc_flag out_status nvcc_bin flags) 37 | set(preprocess_empty_cu_file "--dryrun" "-E" "-x" "cu" "/dev/null") 38 | set(nvcc_command ${flags} ${preprocess_empty_cu_file}) 39 | # Run nvcc and check the exit status 40 | execute_process(COMMAND ${nvcc_bin} ${nvcc_command} 41 | RESULT_VARIABLE tmp_out_status 42 | OUTPUT_QUIET 43 | ERROR_QUIET) 44 | if (${tmp_out_status} EQUAL 0) 45 | set(${out_status} TRUE PARENT_SCOPE) 46 | else() 47 | set(${out_status} FALSE PARENT_SCOPE) 48 | endif() 49 | endfunction() 50 | 51 | # Given the list of arch values, check which are supported by 52 | # nvcc found in CUDA_TOOLKIT_ROOT_DIR. Requires CUDA to be set up in CMake. 53 | # 54 | # @param out_arch_values_allowed List of arch values supported by nvcc 55 | # @param arch_values_to_check List of values to be checked against nvcc 56 | # for example: 60;61;70;75 57 | # @return out_arch_values_allowed 58 | function(CUDA_find_supported_arch_values out_arch_values_allowed arch_values_to_check) 59 | if (NOT CUDA_FOUND) 60 | message(ERROR "CUDA is needed to check supported architecture values") 61 | endif() 62 | # allow the user to pass the list like a normal variable 63 | set(arch_list ${arch_values_to_check} ${ARGN}) 64 | set(nvcc "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc") 65 | foreach(arch IN LISTS arch_list ITEMS) 66 | CUDA_check_nvcc_flag(supported ${nvcc} "-arch=sm_${arch}") 67 | if (supported) 68 | set(out_list ${out_list} ${arch}) 69 | endif() 70 | endforeach(arch) 71 | set(${out_arch_values_allowed} ${out_list} PARENT_SCOPE) 72 | endfunction() 73 | 74 | # Generate -gencode arch=compute_XX,code=sm_XX for list of supported arch values 75 | # List should be sorted in increasing order. 76 | # The last arch value will be repeated as -gencode arch=compute_XX,code=compute_XX 77 | # to ensure the generation of PTX for most recent virtual architecture 78 | # and maintain forward compatibility 79 | # 80 | # @param out_args_string output string containing appropriate CUDA_NVCC_FLAGS 81 | # @param arch_values list of arch values to use 82 | # @return out_args_string 83 | function(CUDA_get_gencode_args out_args_string arch_values) 84 | # allow the user to pass the list like a normal variable 85 | set(arch_list ${arch_values} ${ARGN}) 86 | set(out "") 87 | foreach(arch IN LISTS arch_list) 88 | set(out "${out} -gencode arch=compute_${arch},code=sm_${arch}") 89 | endforeach(arch) 90 | # Repeat the last one as to ensure the generation of PTX for most 91 | # recent virtual architecture for forward compatibility 92 | list(GET arch_list -1 last_arch) 93 | set(out "${out} -gencode arch=compute_${last_arch},code=compute_${last_arch}") 94 | set(${out_args_string} ${out} PARENT_SCOPE) 95 | endfunction() 96 | -------------------------------------------------------------------------------- /plugin/pybind11/.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | image: 3 | - Visual Studio 2017 4 | - Visual Studio 2015 5 | test: off 6 | skip_branch_with_pr: true 7 | build: 8 | parallel: true 9 | platform: 10 | - x64 11 | - x86 12 | environment: 13 | matrix: 14 | - PYTHON: 36 15 | CPP: 14 16 | CONFIG: Debug 17 | - PYTHON: 27 18 | CPP: 14 19 | CONFIG: Debug 20 | - CONDA: 36 21 | CPP: latest 22 | CONFIG: Release 23 | matrix: 24 | exclude: 25 | - image: Visual Studio 2015 26 | platform: x86 27 | - image: Visual Studio 2015 28 | CPP: latest 29 | - image: Visual Studio 2017 30 | CPP: latest 31 | platform: x86 32 | install: 33 | - ps: | 34 | if ($env:PLATFORM -eq "x64") { $env:CMAKE_ARCH = "x64" } 35 | if ($env:APPVEYOR_JOB_NAME -like "*Visual Studio 2017*") { 36 | $env:CMAKE_GENERATOR = "Visual Studio 15 2017" 37 | $env:CMAKE_INCLUDE_PATH = "C:\Libraries\boost_1_64_0" 38 | $env:CXXFLAGS = "-permissive-" 39 | } else { 40 | $env:CMAKE_GENERATOR = "Visual Studio 14 2015" 41 | } 42 | if ($env:PYTHON) { 43 | if ($env:PLATFORM -eq "x64") { $env:PYTHON = "$env:PYTHON-x64" } 44 | $env:PATH = "C:\Python$env:PYTHON\;C:\Python$env:PYTHON\Scripts\;$env:PATH" 45 | python -W ignore -m pip install --upgrade pip wheel 46 | python -W ignore -m pip install pytest numpy --no-warn-script-location 47 | } elseif ($env:CONDA) { 48 | if ($env:CONDA -eq "27") { $env:CONDA = "" } 49 | if ($env:PLATFORM -eq "x64") { $env:CONDA = "$env:CONDA-x64" } 50 | $env:PATH = "C:\Miniconda$env:CONDA\;C:\Miniconda$env:CONDA\Scripts\;$env:PATH" 51 | $env:PYTHONHOME = "C:\Miniconda$env:CONDA" 52 | conda --version 53 | conda install -y -q pytest numpy scipy 54 | } 55 | - ps: | 56 | Start-FileDownload 'http://bitbucket.org/eigen/eigen/get/3.3.3.zip' 57 | 7z x 3.3.3.zip -y > $null 58 | $env:CMAKE_INCLUDE_PATH = "eigen-eigen-67e894c6cd8f;$env:CMAKE_INCLUDE_PATH" 59 | build_script: 60 | - cmake -G "%CMAKE_GENERATOR%" -A "%CMAKE_ARCH%" 61 | -DPYBIND11_CPP_STANDARD=/std:c++%CPP% 62 | -DPYBIND11_WERROR=ON 63 | -DDOWNLOAD_CATCH=ON 64 | -DCMAKE_SUPPRESS_REGENERATION=1 65 | . 66 | - set MSBuildLogger="C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" 67 | - cmake --build . --config %CONFIG% --target pytest -- /m /v:m /logger:%MSBuildLogger% 68 | - cmake --build . --config %CONFIG% --target cpptest -- /m /v:m /logger:%MSBuildLogger% 69 | - if "%CPP%"=="latest" (cmake --build . --config %CONFIG% --target test_cmake_build -- /m /v:m /logger:%MSBuildLogger%) 70 | on_failure: if exist "tests\test_cmake_build" type tests\test_cmake_build\*.log* 71 | -------------------------------------------------------------------------------- /plugin/pybind11/.gitignore: -------------------------------------------------------------------------------- 1 | CMakeCache.txt 2 | CMakeFiles 3 | Makefile 4 | cmake_install.cmake 5 | .DS_Store 6 | *.so 7 | *.pyd 8 | *.dll 9 | *.sln 10 | *.sdf 11 | *.opensdf 12 | *.vcxproj 13 | *.filters 14 | example.dir 15 | Win32 16 | x64 17 | Release 18 | Debug 19 | .vs 20 | CTestTestfile.cmake 21 | Testing 22 | autogen 23 | MANIFEST 24 | /.ninja_* 25 | /*.ninja 26 | /docs/.build 27 | *.py[co] 28 | *.egg-info 29 | *~ 30 | .*.swp 31 | .DS_Store 32 | /dist 33 | /build 34 | /cmake/ 35 | .cache/ 36 | sosize-*.txt 37 | pybind11Config*.cmake 38 | pybind11Targets.cmake 39 | -------------------------------------------------------------------------------- /plugin/pybind11/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tools/clang"] 2 | path = tools/clang 3 | url = ../../wjakob/clang-cindex-python3 4 | -------------------------------------------------------------------------------- /plugin/pybind11/.readthedocs.yml: -------------------------------------------------------------------------------- 1 | python: 2 | version: 3 3 | requirements_file: docs/requirements.txt 4 | -------------------------------------------------------------------------------- /plugin/pybind11/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Thank you for your interest in this project! Please refer to the following 2 | sections on how to contribute code and bug reports. 3 | 4 | ### Reporting bugs 5 | 6 | At the moment, this project is run in the spare time of a single person 7 | ([Wenzel Jakob](http://rgl.epfl.ch/people/wjakob)) with very limited resources 8 | for issue tracker tickets. Thus, before submitting a question or bug report, 9 | please take a moment of your time and ensure that your issue isn't already 10 | discussed in the project documentation provided at 11 | [http://pybind11.readthedocs.org/en/latest](http://pybind11.readthedocs.org/en/latest). 12 | 13 | Assuming that you have identified a previously unknown problem or an important 14 | question, it's essential that you submit a self-contained and minimal piece of 15 | code that reproduces the problem. In other words: no external dependencies, 16 | isolate the function(s) that cause breakage, submit matched and complete C++ 17 | and Python snippets that can be easily compiled and run on my end. 18 | 19 | ## Pull requests 20 | Contributions are submitted, reviewed, and accepted using Github pull requests. 21 | Please refer to [this 22 | article](https://help.github.com/articles/using-pull-requests) for details and 23 | adhere to the following rules to make the process as smooth as possible: 24 | 25 | * Make a new branch for every feature you're working on. 26 | * Make small and clean pull requests that are easy to review but make sure they 27 | do add value by themselves. 28 | * Add tests for any new functionality and run the test suite (``make pytest``) 29 | to ensure that no existing features break. 30 | * Please run ``flake8`` and ``tools/check-style.sh`` to check your code matches 31 | the project style. (Note that ``check-style.sh`` requires ``gawk``.) 32 | * This project has a strong focus on providing general solutions using a 33 | minimal amount of code, thus small pull requests are greatly preferred. 34 | 35 | ### Licensing of contributions 36 | 37 | pybind11 is provided under a BSD-style license that can be found in the 38 | ``LICENSE`` file. By using, distributing, or contributing to this project, you 39 | agree to the terms and conditions of this license. 40 | 41 | You are under no obligation whatsoever to provide any bug fixes, patches, or 42 | upgrades to the features, functionality or performance of the source code 43 | ("Enhancements") to anyone; however, if you choose to make your Enhancements 44 | available either publicly, or directly to the author of this software, without 45 | imposing a separate written license agreement for such Enhancements, then you 46 | hereby grant the following license: a non-exclusive, royalty-free perpetual 47 | license to install, use, modify, prepare derivative works, incorporate into 48 | other computer software, distribute, and sublicense such enhancements or 49 | derivative works thereof, in binary and source code form. 50 | -------------------------------------------------------------------------------- /plugin/pybind11/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Make sure you've completed the following steps before submitting your issue -- thank you! 2 | 3 | 1. Check if your question has already been answered in the [FAQ](http://pybind11.readthedocs.io/en/latest/faq.html) section. 4 | 2. Make sure you've read the [documentation](http://pybind11.readthedocs.io/en/latest/). Your issue may be addressed there. 5 | 3. If those resources didn't help and you only have a short question (not a bug report), consider asking in the [Gitter chat room](https://gitter.im/pybind/Lobby). 6 | 4. If you have a genuine bug report or a more complex question which is not answered in the previous items (or not suitable for chat), please fill in the details below. 7 | 5. Include a self-contained and minimal piece of code that reproduces the problem. If that's not possible, try to make the description as clear as possible. 8 | 9 | *After reading, remove this checklist and the template text in parentheses below.* 10 | 11 | ## Issue description 12 | 13 | (Provide a short description, state the expected behavior and what actually happens.) 14 | 15 | ## Reproducible example code 16 | 17 | (The code should be minimal, have no external dependencies, isolate the function(s) that cause breakage. Submit matched and complete C++ and Python snippets that can be easily compiled and run to diagnose the issue.) 18 | -------------------------------------------------------------------------------- /plugin/pybind11/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Wenzel Jakob , All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | 9 | 2. Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | 3. Neither the name of the copyright holder nor the names of its contributors 14 | may be used to endorse or promote products derived from this software 15 | without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 21 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 24 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 25 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | 28 | Please also refer to the file CONTRIBUTING.md, which clarifies licensing of 29 | external contributions to this project including patches, pull requests, etc. 30 | -------------------------------------------------------------------------------- /plugin/pybind11/MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include include/pybind11 *.h 2 | include LICENSE README.md CONTRIBUTING.md 3 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/Doxyfile: -------------------------------------------------------------------------------- 1 | PROJECT_NAME = pybind11 2 | INPUT = ../include/pybind11/ 3 | RECURSIVE = YES 4 | 5 | GENERATE_HTML = NO 6 | GENERATE_LATEX = NO 7 | GENERATE_XML = YES 8 | XML_OUTPUT = .build/doxygenxml 9 | XML_PROGRAMLISTING = YES 10 | 11 | MACRO_EXPANSION = YES 12 | EXPAND_ONLY_PREDEF = YES 13 | EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION 14 | 15 | ALIASES = "rst=\verbatim embed:rst" 16 | ALIASES += "endrst=\endverbatim" 17 | 18 | QUIET = YES 19 | WARNINGS = YES 20 | WARN_IF_UNDOCUMENTED = NO 21 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/_static/theme_overrides.css: -------------------------------------------------------------------------------- 1 | .wy-table-responsive table td, 2 | .wy-table-responsive table th { 3 | white-space: initial !important; 4 | } 5 | .rst-content table.docutils td { 6 | vertical-align: top !important; 7 | } 8 | div[class^='highlight'] pre { 9 | white-space: pre; 10 | white-space: pre-wrap; 11 | } 12 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/advanced/cast/chrono.rst: -------------------------------------------------------------------------------- 1 | Chrono 2 | ====== 3 | 4 | When including the additional header file :file:`pybind11/chrono.h` conversions 5 | from C++11 chrono datatypes to python datetime objects are automatically enabled. 6 | This header also enables conversions of python floats (often from sources such 7 | as ``time.monotonic()``, ``time.perf_counter()`` and ``time.process_time()``) 8 | into durations. 9 | 10 | An overview of clocks in C++11 11 | ------------------------------ 12 | 13 | A point of confusion when using these conversions is the differences between 14 | clocks provided in C++11. There are three clock types defined by the C++11 15 | standard and users can define their own if needed. Each of these clocks have 16 | different properties and when converting to and from python will give different 17 | results. 18 | 19 | The first clock defined by the standard is ``std::chrono::system_clock``. This 20 | clock measures the current date and time. However, this clock changes with to 21 | updates to the operating system time. For example, if your time is synchronised 22 | with a time server this clock will change. This makes this clock a poor choice 23 | for timing purposes but good for measuring the wall time. 24 | 25 | The second clock defined in the standard is ``std::chrono::steady_clock``. 26 | This clock ticks at a steady rate and is never adjusted. This makes it excellent 27 | for timing purposes, however the value in this clock does not correspond to the 28 | current date and time. Often this clock will be the amount of time your system 29 | has been on, although it does not have to be. This clock will never be the same 30 | clock as the system clock as the system clock can change but steady clocks 31 | cannot. 32 | 33 | The third clock defined in the standard is ``std::chrono::high_resolution_clock``. 34 | This clock is the clock that has the highest resolution out of the clocks in the 35 | system. It is normally a typedef to either the system clock or the steady clock 36 | but can be its own independent clock. This is important as when using these 37 | conversions as the types you get in python for this clock might be different 38 | depending on the system. 39 | If it is a typedef of the system clock, python will get datetime objects, but if 40 | it is a different clock they will be timedelta objects. 41 | 42 | Provided conversions 43 | -------------------- 44 | 45 | .. rubric:: C++ to Python 46 | 47 | - ``std::chrono::system_clock::time_point`` → ``datetime.datetime`` 48 | System clock times are converted to python datetime instances. They are 49 | in the local timezone, but do not have any timezone information attached 50 | to them (they are naive datetime objects). 51 | 52 | - ``std::chrono::duration`` → ``datetime.timedelta`` 53 | Durations are converted to timedeltas, any precision in the duration 54 | greater than microseconds is lost by rounding towards zero. 55 | 56 | - ``std::chrono::[other_clocks]::time_point`` → ``datetime.timedelta`` 57 | Any clock time that is not the system clock is converted to a time delta. 58 | This timedelta measures the time from the clocks epoch to now. 59 | 60 | .. rubric:: Python to C++ 61 | 62 | - ``datetime.datetime`` or ``datetime.date`` or ``datetime.time`` → ``std::chrono::system_clock::time_point`` 63 | Date/time objects are converted into system clock timepoints. Any 64 | timezone information is ignored and the type is treated as a naive 65 | object. 66 | 67 | - ``datetime.timedelta`` → ``std::chrono::duration`` 68 | Time delta are converted into durations with microsecond precision. 69 | 70 | - ``datetime.timedelta`` → ``std::chrono::[other_clocks]::time_point`` 71 | Time deltas that are converted into clock timepoints are treated as 72 | the amount of time from the start of the clocks epoch. 73 | 74 | - ``float`` → ``std::chrono::duration`` 75 | Floats that are passed to C++ as durations be interpreted as a number of 76 | seconds. These will be converted to the duration using ``duration_cast`` 77 | from the float. 78 | 79 | - ``float`` → ``std::chrono::[other_clocks]::time_point`` 80 | Floats that are passed to C++ as time points will be interpreted as the 81 | number of seconds from the start of the clocks epoch. 82 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/advanced/cast/custom.rst: -------------------------------------------------------------------------------- 1 | Custom type casters 2 | =================== 3 | 4 | In very rare cases, applications may require custom type casters that cannot be 5 | expressed using the abstractions provided by pybind11, thus requiring raw 6 | Python C API calls. This is fairly advanced usage and should only be pursued by 7 | experts who are familiar with the intricacies of Python reference counting. 8 | 9 | The following snippets demonstrate how this works for a very simple ``inty`` 10 | type that that should be convertible from Python types that provide a 11 | ``__int__(self)`` method. 12 | 13 | .. code-block:: cpp 14 | 15 | struct inty { long long_value; }; 16 | 17 | void print(inty s) { 18 | std::cout << s.long_value << std::endl; 19 | } 20 | 21 | The following Python snippet demonstrates the intended usage from the Python side: 22 | 23 | .. code-block:: python 24 | 25 | class A: 26 | def __int__(self): 27 | return 123 28 | 29 | from example import print 30 | print(A()) 31 | 32 | To register the necessary conversion routines, it is necessary to add 33 | a partial overload to the ``pybind11::detail::type_caster`` template. 34 | Although this is an implementation detail, adding partial overloads to this 35 | type is explicitly allowed. 36 | 37 | .. code-block:: cpp 38 | 39 | namespace pybind11 { namespace detail { 40 | template <> struct type_caster { 41 | public: 42 | /** 43 | * This macro establishes the name 'inty' in 44 | * function signatures and declares a local variable 45 | * 'value' of type inty 46 | */ 47 | PYBIND11_TYPE_CASTER(inty, _("inty")); 48 | 49 | /** 50 | * Conversion part 1 (Python->C++): convert a PyObject into a inty 51 | * instance or return false upon failure. The second argument 52 | * indicates whether implicit conversions should be applied. 53 | */ 54 | bool load(handle src, bool) { 55 | /* Extract PyObject from handle */ 56 | PyObject *source = src.ptr(); 57 | /* Try converting into a Python integer value */ 58 | PyObject *tmp = PyNumber_Long(source); 59 | if (!tmp) 60 | return false; 61 | /* Now try to convert into a C++ int */ 62 | value.long_value = PyLong_AsLong(tmp); 63 | Py_DECREF(tmp); 64 | /* Ensure return code was OK (to avoid out-of-range errors etc) */ 65 | return !(value.long_value == -1 && !PyErr_Occurred()); 66 | } 67 | 68 | /** 69 | * Conversion part 2 (C++ -> Python): convert an inty instance into 70 | * a Python object. The second and third arguments are used to 71 | * indicate the return value policy and parent object (for 72 | * ``return_value_policy::reference_internal``) and are generally 73 | * ignored by implicit casters. 74 | */ 75 | static handle cast(inty src, return_value_policy /* policy */, handle /* parent */) { 76 | return PyLong_FromLong(src.long_value); 77 | } 78 | }; 79 | }} // namespace pybind11::detail 80 | 81 | .. note:: 82 | 83 | A ``type_caster`` defined with ``PYBIND11_TYPE_CASTER(T, ...)`` requires 84 | that ``T`` is default-constructible (``value`` is first default constructed 85 | and then ``load()`` assigns to it). 86 | 87 | .. warning:: 88 | 89 | When using custom type casters, it's important to declare them consistently 90 | in every compilation unit of the Python extension module. Otherwise, 91 | undefined behavior can ensue. 92 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/advanced/cast/functional.rst: -------------------------------------------------------------------------------- 1 | Functional 2 | ########## 3 | 4 | The following features must be enabled by including :file:`pybind11/functional.h`. 5 | 6 | 7 | Callbacks and passing anonymous functions 8 | ========================================= 9 | 10 | The C++11 standard brought lambda functions and the generic polymorphic 11 | function wrapper ``std::function<>`` to the C++ programming language, which 12 | enable powerful new ways of working with functions. Lambda functions come in 13 | two flavors: stateless lambda function resemble classic function pointers that 14 | link to an anonymous piece of code, while stateful lambda functions 15 | additionally depend on captured variables that are stored in an anonymous 16 | *lambda closure object*. 17 | 18 | Here is a simple example of a C++ function that takes an arbitrary function 19 | (stateful or stateless) with signature ``int -> int`` as an argument and runs 20 | it with the value 10. 21 | 22 | .. code-block:: cpp 23 | 24 | int func_arg(const std::function &f) { 25 | return f(10); 26 | } 27 | 28 | The example below is more involved: it takes a function of signature ``int -> int`` 29 | and returns another function of the same kind. The return value is a stateful 30 | lambda function, which stores the value ``f`` in the capture object and adds 1 to 31 | its return value upon execution. 32 | 33 | .. code-block:: cpp 34 | 35 | std::function func_ret(const std::function &f) { 36 | return [f](int i) { 37 | return f(i) + 1; 38 | }; 39 | } 40 | 41 | This example demonstrates using python named parameters in C++ callbacks which 42 | requires using ``py::cpp_function`` as a wrapper. Usage is similar to defining 43 | methods of classes: 44 | 45 | .. code-block:: cpp 46 | 47 | py::cpp_function func_cpp() { 48 | return py::cpp_function([](int i) { return i+1; }, 49 | py::arg("number")); 50 | } 51 | 52 | After including the extra header file :file:`pybind11/functional.h`, it is almost 53 | trivial to generate binding code for all of these functions. 54 | 55 | .. code-block:: cpp 56 | 57 | #include 58 | 59 | PYBIND11_MODULE(example, m) { 60 | m.def("func_arg", &func_arg); 61 | m.def("func_ret", &func_ret); 62 | m.def("func_cpp", &func_cpp); 63 | } 64 | 65 | The following interactive session shows how to call them from Python. 66 | 67 | .. code-block:: pycon 68 | 69 | $ python 70 | >>> import example 71 | >>> def square(i): 72 | ... return i * i 73 | ... 74 | >>> example.func_arg(square) 75 | 100L 76 | >>> square_plus_1 = example.func_ret(square) 77 | >>> square_plus_1(4) 78 | 17L 79 | >>> plus_1 = func_cpp() 80 | >>> plus_1(number=43) 81 | 44L 82 | 83 | .. warning:: 84 | 85 | Keep in mind that passing a function from C++ to Python (or vice versa) 86 | will instantiate a piece of wrapper code that translates function 87 | invocations between the two languages. Naturally, this translation 88 | increases the computational cost of each function call somewhat. A 89 | problematic situation can arise when a function is copied back and forth 90 | between Python and C++ many times in a row, in which case the underlying 91 | wrappers will accumulate correspondingly. The resulting long sequence of 92 | C++ -> Python -> C++ -> ... roundtrips can significantly decrease 93 | performance. 94 | 95 | There is one exception: pybind11 detects case where a stateless function 96 | (i.e. a function pointer or a lambda function without captured variables) 97 | is passed as an argument to another C++ function exposed in Python. In this 98 | case, there is no overhead. Pybind11 will extract the underlying C++ 99 | function pointer from the wrapped function to sidestep a potential C++ -> 100 | Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`. 101 | 102 | .. note:: 103 | 104 | This functionality is very useful when generating bindings for callbacks in 105 | C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.). 106 | 107 | The file :file:`tests/test_callbacks.cpp` contains a complete example 108 | that demonstrates how to work with callbacks and anonymous functions in 109 | more detail. 110 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/advanced/cast/index.rst: -------------------------------------------------------------------------------- 1 | Type conversions 2 | ################ 3 | 4 | Apart from enabling cross-language function calls, a fundamental problem 5 | that a binding tool like pybind11 must address is to provide access to 6 | native Python types in C++ and vice versa. There are three fundamentally 7 | different ways to do this—which approach is preferable for a particular type 8 | depends on the situation at hand. 9 | 10 | 1. Use a native C++ type everywhere. In this case, the type must be wrapped 11 | using pybind11-generated bindings so that Python can interact with it. 12 | 13 | 2. Use a native Python type everywhere. It will need to be wrapped so that 14 | C++ functions can interact with it. 15 | 16 | 3. Use a native C++ type on the C++ side and a native Python type on the 17 | Python side. pybind11 refers to this as a *type conversion*. 18 | 19 | Type conversions are the most "natural" option in the sense that native 20 | (non-wrapped) types are used everywhere. The main downside is that a copy 21 | of the data must be made on every Python ↔ C++ transition: this is 22 | needed since the C++ and Python versions of the same type generally won't 23 | have the same memory layout. 24 | 25 | pybind11 can perform many kinds of conversions automatically. An overview 26 | is provided in the table ":ref:`conversion_table`". 27 | 28 | The following subsections discuss the differences between these options in more 29 | detail. The main focus in this section is on type conversions, which represent 30 | the last case of the above list. 31 | 32 | .. toctree:: 33 | :maxdepth: 1 34 | 35 | overview 36 | strings 37 | stl 38 | functional 39 | chrono 40 | eigen 41 | custom 42 | 43 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/advanced/pycpp/index.rst: -------------------------------------------------------------------------------- 1 | Python C++ interface 2 | #################### 3 | 4 | pybind11 exposes Python types and functions using thin C++ wrappers, which 5 | makes it possible to conveniently call Python code from C++ without resorting 6 | to Python's C API. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | object 12 | numpy 13 | utilities 14 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/benchmark.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | import time 4 | import datetime as dt 5 | 6 | nfns = 4 # Functions per class 7 | nargs = 4 # Arguments per function 8 | 9 | 10 | def generate_dummy_code_pybind11(nclasses=10): 11 | decl = "" 12 | bindings = "" 13 | 14 | for cl in range(nclasses): 15 | decl += "class cl%03i;\n" % cl 16 | decl += '\n' 17 | 18 | for cl in range(nclasses): 19 | decl += "class cl%03i {\n" % cl 20 | decl += "public:\n" 21 | bindings += ' py::class_(m, "cl%03i")\n' % (cl, cl) 22 | for fn in range(nfns): 23 | ret = random.randint(0, nclasses - 1) 24 | params = [random.randint(0, nclasses - 1) for i in range(nargs)] 25 | decl += " cl%03i *fn_%03i(" % (ret, fn) 26 | decl += ", ".join("cl%03i *" % p for p in params) 27 | decl += ");\n" 28 | bindings += ' .def("fn_%03i", &cl%03i::fn_%03i)\n' % \ 29 | (fn, cl, fn) 30 | decl += "};\n\n" 31 | bindings += ' ;\n' 32 | 33 | result = "#include \n\n" 34 | result += "namespace py = pybind11;\n\n" 35 | result += decl + '\n' 36 | result += "PYBIND11_MODULE(example, m) {\n" 37 | result += bindings 38 | result += "}" 39 | return result 40 | 41 | 42 | def generate_dummy_code_boost(nclasses=10): 43 | decl = "" 44 | bindings = "" 45 | 46 | for cl in range(nclasses): 47 | decl += "class cl%03i;\n" % cl 48 | decl += '\n' 49 | 50 | for cl in range(nclasses): 51 | decl += "class cl%03i {\n" % cl 52 | decl += "public:\n" 53 | bindings += ' py::class_("cl%03i")\n' % (cl, cl) 54 | for fn in range(nfns): 55 | ret = random.randint(0, nclasses - 1) 56 | params = [random.randint(0, nclasses - 1) for i in range(nargs)] 57 | decl += " cl%03i *fn_%03i(" % (ret, fn) 58 | decl += ", ".join("cl%03i *" % p for p in params) 59 | decl += ");\n" 60 | bindings += ' .def("fn_%03i", &cl%03i::fn_%03i, py::return_value_policy())\n' % \ 61 | (fn, cl, fn) 62 | decl += "};\n\n" 63 | bindings += ' ;\n' 64 | 65 | result = "#include \n\n" 66 | result += "namespace py = boost::python;\n\n" 67 | result += decl + '\n' 68 | result += "BOOST_PYTHON_MODULE(example) {\n" 69 | result += bindings 70 | result += "}" 71 | return result 72 | 73 | 74 | for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]: 75 | print ("{") 76 | for i in range(0, 10): 77 | nclasses = 2 ** i 78 | with open("test.cpp", "w") as f: 79 | f.write(codegen(nclasses)) 80 | n1 = dt.datetime.now() 81 | os.system("g++ -Os -shared -rdynamic -undefined dynamic_lookup " 82 | "-fvisibility=hidden -std=c++14 test.cpp -I include " 83 | "-I /System/Library/Frameworks/Python.framework/Headers -o test.so") 84 | n2 = dt.datetime.now() 85 | elapsed = (n2 - n1).total_seconds() 86 | size = os.stat('test.so').st_size 87 | print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size)) 88 | print ("}") 89 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/benchmark.rst: -------------------------------------------------------------------------------- 1 | Benchmark 2 | ========= 3 | 4 | The following is the result of a synthetic benchmark comparing both compilation 5 | time and module size of pybind11 against Boost.Python. A detailed report about a 6 | Boost.Python to pybind11 conversion of a real project is available here: [#f1]_. 7 | 8 | .. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf 9 | 10 | Setup 11 | ----- 12 | 13 | A python script (see the ``docs/benchmark.py`` file) was used to generate a set 14 | of files with dummy classes whose count increases for each successive benchmark 15 | (between 1 and 2048 classes in powers of two). Each class has four methods with 16 | a randomly generated signature with a return value and four arguments. (There 17 | was no particular reason for this setup other than the desire to generate many 18 | unique function signatures whose count could be controlled in a simple way.) 19 | 20 | Here is an example of the binding code for one class: 21 | 22 | .. code-block:: cpp 23 | 24 | ... 25 | class cl034 { 26 | public: 27 | cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); 28 | cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); 29 | cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); 30 | cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); 31 | }; 32 | ... 33 | 34 | PYBIND11_MODULE(example, m) { 35 | ... 36 | py::class_(m, "cl034") 37 | .def("fn_000", &cl034::fn_000) 38 | .def("fn_001", &cl034::fn_001) 39 | .def("fn_002", &cl034::fn_002) 40 | .def("fn_003", &cl034::fn_003) 41 | ... 42 | } 43 | 44 | The Boost.Python version looks almost identical except that a return value 45 | policy had to be specified as an argument to ``def()``. For both libraries, 46 | compilation was done with 47 | 48 | .. code-block:: bash 49 | 50 | Apple LLVM version 7.0.2 (clang-700.1.81) 51 | 52 | and the following compilation flags 53 | 54 | .. code-block:: bash 55 | 56 | g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14 57 | 58 | Compilation time 59 | ---------------- 60 | 61 | The following log-log plot shows how the compilation time grows for an 62 | increasing number of class and function declarations. pybind11 includes many 63 | fewer headers, which initially leads to shorter compilation times, but the 64 | performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for 65 | the largest largest file with 2048 classes and a total of 8192 methods -- a 66 | modest **1.2x** speedup relative to Boost.Python, which required 116.35 67 | seconds). 68 | 69 | .. only:: not latex 70 | 71 | .. image:: pybind11_vs_boost_python1.svg 72 | 73 | .. only:: latex 74 | 75 | .. image:: pybind11_vs_boost_python1.png 76 | 77 | Module size 78 | ----------- 79 | 80 | Differences between the two libraries become much more pronounced when 81 | considering the file size of the generated Python plugin: for the largest file, 82 | the binary generated by Boost.Python required 16.8 MiB, which was **2.17 83 | times** / **9.1 megabytes** larger than the output generated by pybind11. For 84 | very small inputs, Boost.Python has an edge in the plot below -- however, note 85 | that it stores many definitions in an external library, whose size was not 86 | included here, hence the comparison is slightly shifted in Boost.Python's 87 | favor. 88 | 89 | .. only:: not latex 90 | 91 | .. image:: pybind11_vs_boost_python2.svg 92 | 93 | .. only:: latex 94 | 95 | .. image:: pybind11_vs_boost_python2.png 96 | 97 | 98 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/index.rst: -------------------------------------------------------------------------------- 1 | .. only: not latex 2 | 3 | .. image:: pybind11-logo.png 4 | 5 | pybind11 --- Seamless operability between C++11 and Python 6 | ========================================================== 7 | 8 | .. only: not latex 9 | 10 | Contents: 11 | 12 | .. toctree:: 13 | :maxdepth: 1 14 | 15 | intro 16 | changelog 17 | upgrade 18 | 19 | .. toctree:: 20 | :caption: The Basics 21 | :maxdepth: 2 22 | 23 | basics 24 | classes 25 | compiling 26 | 27 | .. toctree:: 28 | :caption: Advanced Topics 29 | :maxdepth: 2 30 | 31 | advanced/functions 32 | advanced/classes 33 | advanced/exceptions 34 | advanced/smart_ptrs 35 | advanced/cast/index 36 | advanced/pycpp/index 37 | advanced/embedding 38 | advanced/misc 39 | 40 | .. toctree:: 41 | :caption: Extra Information 42 | :maxdepth: 1 43 | 44 | faq 45 | benchmark 46 | limitations 47 | reference 48 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/intro.rst: -------------------------------------------------------------------------------- 1 | .. image:: pybind11-logo.png 2 | 3 | About this project 4 | ================== 5 | **pybind11** is a lightweight header-only library that exposes C++ types in Python 6 | and vice versa, mainly to create Python bindings of existing C++ code. Its 7 | goals and syntax are similar to the excellent `Boost.Python`_ library by David 8 | Abrahams: to minimize boilerplate code in traditional extension modules by 9 | inferring type information using compile-time introspection. 10 | 11 | .. _Boost.Python: http://www.boost.org/doc/libs/release/libs/python/doc/index.html 12 | 13 | The main issue with Boost.Python—and the reason for creating such a similar 14 | project—is Boost. Boost is an enormously large and complex suite of utility 15 | libraries that works with almost every C++ compiler in existence. This 16 | compatibility has its cost: arcane template tricks and workarounds are 17 | necessary to support the oldest and buggiest of compiler specimens. Now that 18 | C++11-compatible compilers are widely available, this heavy machinery has 19 | become an excessively large and unnecessary dependency. 20 | Think of this library as a tiny self-contained version of Boost.Python with 21 | everything stripped away that isn't relevant for binding generation. Without 22 | comments, the core header files only require ~4K lines of code and depend on 23 | Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This 24 | compact implementation was possible thanks to some of the new C++11 language 25 | features (specifically: tuples, lambda functions and variadic templates). Since 26 | its creation, this library has grown beyond Boost.Python in many ways, leading 27 | to dramatically simpler binding code in many common situations. 28 | 29 | Core features 30 | ************* 31 | The following core C++ features can be mapped to Python 32 | 33 | - Functions accepting and returning custom data structures per value, reference, or pointer 34 | - Instance methods and static methods 35 | - Overloaded functions 36 | - Instance attributes and static attributes 37 | - Arbitrary exception types 38 | - Enumerations 39 | - Callbacks 40 | - Iterators and ranges 41 | - Custom operators 42 | - Single and multiple inheritance 43 | - STL data structures 44 | - Smart pointers with reference counting like ``std::shared_ptr`` 45 | - Internal references with correct reference counting 46 | - C++ classes with virtual (and pure virtual) methods can be extended in Python 47 | 48 | Goodies 49 | ******* 50 | In addition to the core functionality, pybind11 provides some extra goodies: 51 | 52 | - Python 2.7, 3.x, and PyPy (PyPy2.7 >= 5.7) are supported with an 53 | implementation-agnostic interface. 54 | 55 | - It is possible to bind C++11 lambda functions with captured variables. The 56 | lambda capture data is stored inside the resulting Python function object. 57 | 58 | - pybind11 uses C++11 move constructors and move assignment operators whenever 59 | possible to efficiently transfer custom data types. 60 | 61 | - It's easy to expose the internal storage of custom data types through 62 | Pythons' buffer protocols. This is handy e.g. for fast conversion between 63 | C++ matrix classes like Eigen and NumPy without expensive copy operations. 64 | 65 | - pybind11 can automatically vectorize functions so that they are transparently 66 | applied to all entries of one or more NumPy array arguments. 67 | 68 | - Python's slice-based access and assignment operations can be supported with 69 | just a few lines of code. 70 | 71 | - Everything is contained in just a few header files; there is no need to link 72 | against any additional libraries. 73 | 74 | - Binaries are generally smaller by a factor of at least 2 compared to 75 | equivalent bindings generated by Boost.Python. A recent pybind11 conversion 76 | of `PyRosetta`_, an enormous Boost.Python binding project, reported a binary 77 | size reduction of **5.4x** and compile time reduction by **5.8x**. 78 | 79 | - Function signatures are precomputed at compile time (using ``constexpr``), 80 | leading to smaller binaries. 81 | 82 | - With little extra effort, C++ types can be pickled and unpickled similar to 83 | regular Python objects. 84 | 85 | .. _PyRosetta: http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf 86 | 87 | Supported compilers 88 | ******************* 89 | 90 | 1. Clang/LLVM (any non-ancient version with C++11 support) 91 | 2. GCC 4.8 or newer 92 | 3. Microsoft Visual Studio 2015 or newer 93 | 4. Intel C++ compiler v17 or newer (v16 with pybind11 v2.0 and v15 with pybind11 v2.0 and a `workaround `_ ) 94 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/limitations.rst: -------------------------------------------------------------------------------- 1 | Limitations 2 | ########### 3 | 4 | pybind11 strives to be a general solution to binding generation, but it also has 5 | certain limitations: 6 | 7 | - pybind11 casts away ``const``-ness in function arguments and return values. 8 | This is in line with the Python language, which has no concept of ``const`` 9 | values. This means that some additional care is needed to avoid bugs that 10 | would be caught by the type checker in a traditional C++ program. 11 | 12 | - The NumPy interface ``pybind11::array`` greatly simplifies accessing 13 | numerical data from C++ (and vice versa), but it's not a full-blown array 14 | class like ``Eigen::Array`` or ``boost.multi_array``. 15 | 16 | These features could be implemented but would lead to a significant increase in 17 | complexity. I've decided to draw the line here to keep this project simple and 18 | compact. Users who absolutely require these features are encouraged to fork 19 | pybind11. 20 | 21 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/pybind11-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/plugin/pybind11/docs/pybind11-logo.png -------------------------------------------------------------------------------- /plugin/pybind11/docs/pybind11_vs_boost_python1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/plugin/pybind11/docs/pybind11_vs_boost_python1.png -------------------------------------------------------------------------------- /plugin/pybind11/docs/pybind11_vs_boost_python2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/plugin/pybind11/docs/pybind11_vs_boost_python2.png -------------------------------------------------------------------------------- /plugin/pybind11/docs/reference.rst: -------------------------------------------------------------------------------- 1 | .. _reference: 2 | 3 | .. warning:: 4 | 5 | Please be advised that the reference documentation discussing pybind11 6 | internals is currently incomplete. Please refer to the previous sections 7 | and the pybind11 header files for the nitty gritty details. 8 | 9 | Reference 10 | ######### 11 | 12 | .. _macros: 13 | 14 | Macros 15 | ====== 16 | 17 | .. doxygendefine:: PYBIND11_MODULE 18 | 19 | .. _core_types: 20 | 21 | Convenience classes for arbitrary Python types 22 | ============================================== 23 | 24 | Common member functions 25 | ----------------------- 26 | 27 | .. doxygenclass:: object_api 28 | :members: 29 | 30 | Without reference counting 31 | -------------------------- 32 | 33 | .. doxygenclass:: handle 34 | :members: 35 | 36 | With reference counting 37 | ----------------------- 38 | 39 | .. doxygenclass:: object 40 | :members: 41 | 42 | .. doxygenfunction:: reinterpret_borrow 43 | 44 | .. doxygenfunction:: reinterpret_steal 45 | 46 | Convenience classes for specific Python types 47 | ============================================= 48 | 49 | .. doxygenclass:: module 50 | :members: 51 | 52 | .. doxygengroup:: pytypes 53 | :members: 54 | 55 | .. _extras: 56 | 57 | Passing extra arguments to ``def`` or ``class_`` 58 | ================================================ 59 | 60 | .. doxygengroup:: annotations 61 | :members: 62 | 63 | Embedding the interpreter 64 | ========================= 65 | 66 | .. doxygendefine:: PYBIND11_EMBEDDED_MODULE 67 | 68 | .. doxygenfunction:: initialize_interpreter 69 | 70 | .. doxygenfunction:: finalize_interpreter 71 | 72 | .. doxygenclass:: scoped_interpreter 73 | 74 | Redirecting C++ streams 75 | ======================= 76 | 77 | .. doxygenclass:: scoped_ostream_redirect 78 | 79 | .. doxygenclass:: scoped_estream_redirect 80 | 81 | .. doxygenfunction:: add_ostream_redirect 82 | 83 | Python built-in functions 84 | ========================= 85 | 86 | .. doxygengroup:: python_builtins 87 | :members: 88 | 89 | Inheritance 90 | =========== 91 | 92 | See :doc:`/classes` and :doc:`/advanced/classes` for more detail. 93 | 94 | .. doxygendefine:: PYBIND11_OVERLOAD 95 | 96 | .. doxygendefine:: PYBIND11_OVERLOAD_PURE 97 | 98 | .. doxygendefine:: PYBIND11_OVERLOAD_NAME 99 | 100 | .. doxygendefine:: PYBIND11_OVERLOAD_PURE_NAME 101 | 102 | .. doxygenfunction:: get_overload 103 | 104 | Exceptions 105 | ========== 106 | 107 | .. doxygenclass:: error_already_set 108 | :members: 109 | 110 | .. doxygenclass:: builtin_exception 111 | :members: 112 | 113 | 114 | Literals 115 | ======== 116 | 117 | .. doxygennamespace:: literals 118 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/release.rst: -------------------------------------------------------------------------------- 1 | To release a new version of pybind11: 2 | 3 | - Update the version number and push to pypi 4 | - Update ``pybind11/_version.py`` (set release version, remove 'dev'). 5 | - Update ``PYBIND11_VERSION_MAJOR`` etc. in ``include/pybind11/detail/common.h``. 6 | - Ensure that all the information in ``setup.py`` is up-to-date. 7 | - Update version in ``docs/conf.py``. 8 | - Tag release date in ``docs/changelog.rst``. 9 | - ``git add`` and ``git commit``. 10 | - if new minor version: ``git checkout -b vX.Y``, ``git push -u origin vX.Y`` 11 | - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'``. 12 | - ``git push`` 13 | - ``git push --tags``. 14 | - ``python setup.py sdist upload``. 15 | - ``python setup.py bdist_wheel upload``. 16 | - Update conda-forge (https://github.com/conda-forge/pybind11-feedstock) via PR 17 | - download release package from Github: ``wget https://github.com/pybind/pybind11/archive/vX.Y.Z.tar.gz`` 18 | - compute checksum: ``shasum -a 256 vX.Y.Z.tar.gz`` 19 | - change version number and checksum in ``recipe/meta.yml`` 20 | - Get back to work 21 | - Update ``_version.py`` (add 'dev' and increment minor). 22 | - Update version in ``docs/conf.py`` 23 | - Update version macros in ``include/pybind11/common.h`` 24 | - ``git add`` and ``git commit``. 25 | ``git push`` 26 | -------------------------------------------------------------------------------- /plugin/pybind11/docs/requirements.txt: -------------------------------------------------------------------------------- 1 | breathe == 4.5.0 2 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/common.h: -------------------------------------------------------------------------------- 1 | #include "detail/common.h" 2 | #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'." 3 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/complex.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/complex.h: Complex number support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "pybind11.h" 13 | #include 14 | 15 | /// glibc defines I as a macro which breaks things, e.g., boost template names 16 | #ifdef I 17 | # undef I 18 | #endif 19 | 20 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 21 | 22 | template struct format_descriptor, detail::enable_if_t::value>> { 23 | static constexpr const char c = format_descriptor::c; 24 | static constexpr const char value[3] = { 'Z', c, '\0' }; 25 | static std::string format() { return std::string(value); } 26 | }; 27 | 28 | #ifndef PYBIND11_CPP17 29 | 30 | template constexpr const char format_descriptor< 31 | std::complex, detail::enable_if_t::value>>::value[3]; 32 | 33 | #endif 34 | 35 | NAMESPACE_BEGIN(detail) 36 | 37 | template struct is_fmt_numeric, detail::enable_if_t::value>> { 38 | static constexpr bool value = true; 39 | static constexpr int index = is_fmt_numeric::index + 3; 40 | }; 41 | 42 | template class type_caster> { 43 | public: 44 | bool load(handle src, bool convert) { 45 | if (!src) 46 | return false; 47 | if (!convert && !PyComplex_Check(src.ptr())) 48 | return false; 49 | Py_complex result = PyComplex_AsCComplex(src.ptr()); 50 | if (result.real == -1.0 && PyErr_Occurred()) { 51 | PyErr_Clear(); 52 | return false; 53 | } 54 | value = std::complex((T) result.real, (T) result.imag); 55 | return true; 56 | } 57 | 58 | static handle cast(const std::complex &src, return_value_policy /* policy */, handle /* parent */) { 59 | return PyComplex_FromDoubles((double) src.real(), (double) src.imag()); 60 | } 61 | 62 | PYBIND11_TYPE_CASTER(std::complex, _("complex")); 63 | }; 64 | NAMESPACE_END(detail) 65 | NAMESPACE_END(PYBIND11_NAMESPACE) 66 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/detail/descr.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "common.h" 13 | 14 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | NAMESPACE_BEGIN(detail) 16 | 17 | #if !defined(_MSC_VER) 18 | # define PYBIND11_DESCR_CONSTEXPR static constexpr 19 | #else 20 | # define PYBIND11_DESCR_CONSTEXPR const 21 | #endif 22 | 23 | /* Concatenate type signatures at compile time */ 24 | template 25 | struct descr { 26 | char text[N + 1]; 27 | 28 | constexpr descr() : text{'\0'} { } 29 | constexpr descr(char const (&s)[N+1]) : descr(s, make_index_sequence()) { } 30 | 31 | template 32 | constexpr descr(char const (&s)[N+1], index_sequence) : text{s[Is]..., '\0'} { } 33 | 34 | template 35 | constexpr descr(char c, Chars... cs) : text{c, static_cast(cs)..., '\0'} { } 36 | 37 | static constexpr std::array types() { 38 | return {{&typeid(Ts)..., nullptr}}; 39 | } 40 | }; 41 | 42 | template 43 | constexpr descr plus_impl(const descr &a, const descr &b, 44 | index_sequence, index_sequence) { 45 | return {a.text[Is1]..., b.text[Is2]...}; 46 | } 47 | 48 | template 49 | constexpr descr operator+(const descr &a, const descr &b) { 50 | return plus_impl(a, b, make_index_sequence(), make_index_sequence()); 51 | } 52 | 53 | template 54 | constexpr descr _(char const(&text)[N]) { return descr(text); } 55 | constexpr descr<0> _(char const(&)[1]) { return {}; } 56 | 57 | template struct int_to_str : int_to_str { }; 58 | template struct int_to_str<0, Digits...> { 59 | static constexpr auto digits = descr(('0' + Digits)...); 60 | }; 61 | 62 | // Ternary description (like std::conditional) 63 | template 64 | constexpr enable_if_t> _(char const(&text1)[N1], char const(&)[N2]) { 65 | return _(text1); 66 | } 67 | template 68 | constexpr enable_if_t> _(char const(&)[N1], char const(&text2)[N2]) { 69 | return _(text2); 70 | } 71 | 72 | template 73 | constexpr enable_if_t _(const T1 &d, const T2 &) { return d; } 74 | template 75 | constexpr enable_if_t _(const T1 &, const T2 &d) { return d; } 76 | 77 | template auto constexpr _() -> decltype(int_to_str::digits) { 78 | return int_to_str::digits; 79 | } 80 | 81 | template constexpr descr<1, Type> _() { return {'%'}; } 82 | 83 | constexpr descr<0> concat() { return {}; } 84 | 85 | template 86 | constexpr descr concat(const descr &descr) { return descr; } 87 | 88 | template 89 | constexpr auto concat(const descr &d, const Args &...args) 90 | -> decltype(std::declval>() + concat(args...)) { 91 | return d + _(", ") + concat(args...); 92 | } 93 | 94 | template 95 | constexpr descr type_descr(const descr &descr) { 96 | return _("{") + descr + _("}"); 97 | } 98 | 99 | NAMESPACE_END(detail) 100 | NAMESPACE_END(PYBIND11_NAMESPACE) 101 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/detail/typeid.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/detail/typeid.h: Compiler-independent access to type identifiers 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include 13 | #include 14 | 15 | #if defined(__GNUG__) 16 | #include 17 | #endif 18 | 19 | #include "common.h" 20 | 21 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 22 | NAMESPACE_BEGIN(detail) 23 | /// Erase all occurrences of a substring 24 | inline void erase_all(std::string &string, const std::string &search) { 25 | for (size_t pos = 0;;) { 26 | pos = string.find(search, pos); 27 | if (pos == std::string::npos) break; 28 | string.erase(pos, search.length()); 29 | } 30 | } 31 | 32 | PYBIND11_NOINLINE inline void clean_type_id(std::string &name) { 33 | #if defined(__GNUG__) 34 | int status = 0; 35 | std::unique_ptr res { 36 | abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free }; 37 | if (status == 0) 38 | name = res.get(); 39 | #else 40 | detail::erase_all(name, "class "); 41 | detail::erase_all(name, "struct "); 42 | detail::erase_all(name, "enum "); 43 | #endif 44 | detail::erase_all(name, "pybind11::"); 45 | } 46 | NAMESPACE_END(detail) 47 | 48 | /// Return a string representation of a C++ type 49 | template static std::string type_id() { 50 | std::string name(typeid(T).name()); 51 | detail::clean_type_id(name); 52 | return name; 53 | } 54 | 55 | NAMESPACE_END(PYBIND11_NAMESPACE) 56 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/eval.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/exec.h: Support for evaluating Python expressions and statements 3 | from strings and files 4 | 5 | Copyright (c) 2016 Klemens Morgenstern and 6 | Wenzel Jakob 7 | 8 | All rights reserved. Use of this source code is governed by a 9 | BSD-style license that can be found in the LICENSE file. 10 | */ 11 | 12 | #pragma once 13 | 14 | #include "pybind11.h" 15 | 16 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 17 | 18 | enum eval_mode { 19 | /// Evaluate a string containing an isolated expression 20 | eval_expr, 21 | 22 | /// Evaluate a string containing a single statement. Returns \c none 23 | eval_single_statement, 24 | 25 | /// Evaluate a string containing a sequence of statement. Returns \c none 26 | eval_statements 27 | }; 28 | 29 | template 30 | object eval(str expr, object global = globals(), object local = object()) { 31 | if (!local) 32 | local = global; 33 | 34 | /* PyRun_String does not accept a PyObject / encoding specifier, 35 | this seems to be the only alternative */ 36 | std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr; 37 | 38 | int start; 39 | switch (mode) { 40 | case eval_expr: start = Py_eval_input; break; 41 | case eval_single_statement: start = Py_single_input; break; 42 | case eval_statements: start = Py_file_input; break; 43 | default: pybind11_fail("invalid evaluation mode"); 44 | } 45 | 46 | PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr()); 47 | if (!result) 48 | throw error_already_set(); 49 | return reinterpret_steal(result); 50 | } 51 | 52 | template 53 | object eval(const char (&s)[N], object global = globals(), object local = object()) { 54 | /* Support raw string literals by removing common leading whitespace */ 55 | auto expr = (s[0] == '\n') ? str(module::import("textwrap").attr("dedent")(s)) 56 | : str(s); 57 | return eval(expr, global, local); 58 | } 59 | 60 | inline void exec(str expr, object global = globals(), object local = object()) { 61 | eval(expr, global, local); 62 | } 63 | 64 | template 65 | void exec(const char (&s)[N], object global = globals(), object local = object()) { 66 | eval(s, global, local); 67 | } 68 | 69 | template 70 | object eval_file(str fname, object global = globals(), object local = object()) { 71 | if (!local) 72 | local = global; 73 | 74 | int start; 75 | switch (mode) { 76 | case eval_expr: start = Py_eval_input; break; 77 | case eval_single_statement: start = Py_single_input; break; 78 | case eval_statements: start = Py_file_input; break; 79 | default: pybind11_fail("invalid evaluation mode"); 80 | } 81 | 82 | int closeFile = 1; 83 | std::string fname_str = (std::string) fname; 84 | #if PY_VERSION_HEX >= 0x03040000 85 | FILE *f = _Py_fopen_obj(fname.ptr(), "r"); 86 | #elif PY_VERSION_HEX >= 0x03000000 87 | FILE *f = _Py_fopen(fname.ptr(), "r"); 88 | #else 89 | /* No unicode support in open() :( */ 90 | auto fobj = reinterpret_steal(PyFile_FromString( 91 | const_cast(fname_str.c_str()), 92 | const_cast("r"))); 93 | FILE *f = nullptr; 94 | if (fobj) 95 | f = PyFile_AsFile(fobj.ptr()); 96 | closeFile = 0; 97 | #endif 98 | if (!f) { 99 | PyErr_Clear(); 100 | pybind11_fail("File \"" + fname_str + "\" could not be opened!"); 101 | } 102 | 103 | #if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION) 104 | PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), 105 | local.ptr()); 106 | (void) closeFile; 107 | #else 108 | PyObject *result = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), 109 | local.ptr(), closeFile); 110 | #endif 111 | 112 | if (!result) 113 | throw error_already_set(); 114 | return reinterpret_steal(result); 115 | } 116 | 117 | NAMESPACE_END(PYBIND11_NAMESPACE) 118 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/functional.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/functional.h: std::function<> support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "pybind11.h" 13 | #include 14 | 15 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 16 | NAMESPACE_BEGIN(detail) 17 | 18 | template 19 | struct type_caster> { 20 | using type = std::function; 21 | using retval_type = conditional_t::value, void_type, Return>; 22 | using function_type = Return (*) (Args...); 23 | 24 | public: 25 | bool load(handle src, bool convert) { 26 | if (src.is_none()) { 27 | // Defer accepting None to other overloads (if we aren't in convert mode): 28 | if (!convert) return false; 29 | return true; 30 | } 31 | 32 | if (!isinstance(src)) 33 | return false; 34 | 35 | auto func = reinterpret_borrow(src); 36 | 37 | /* 38 | When passing a C++ function as an argument to another C++ 39 | function via Python, every function call would normally involve 40 | a full C++ -> Python -> C++ roundtrip, which can be prohibitive. 41 | Here, we try to at least detect the case where the function is 42 | stateless (i.e. function pointer or lambda function without 43 | captured variables), in which case the roundtrip can be avoided. 44 | */ 45 | if (auto cfunc = func.cpp_function()) { 46 | auto c = reinterpret_borrow(PyCFunction_GET_SELF(cfunc.ptr())); 47 | auto rec = (function_record *) c; 48 | 49 | if (rec && rec->is_stateless && 50 | same_type(typeid(function_type), *reinterpret_cast(rec->data[1]))) { 51 | struct capture { function_type f; }; 52 | value = ((capture *) &rec->data)->f; 53 | return true; 54 | } 55 | } 56 | 57 | // ensure GIL is held during functor destruction 58 | struct func_handle { 59 | function f; 60 | func_handle(function&& f_) : f(std::move(f_)) {} 61 | func_handle(const func_handle&) = default; 62 | ~func_handle() { 63 | gil_scoped_acquire acq; 64 | function kill_f(std::move(f)); 65 | } 66 | }; 67 | 68 | // to emulate 'move initialization capture' in C++11 69 | struct func_wrapper { 70 | func_handle hfunc; 71 | func_wrapper(func_handle&& hf): hfunc(std::move(hf)) {} 72 | Return operator()(Args... args) const { 73 | gil_scoped_acquire acq; 74 | object retval(hfunc.f(std::forward(args)...)); 75 | /* Visual studio 2015 parser issue: need parentheses around this expression */ 76 | return (retval.template cast()); 77 | } 78 | }; 79 | 80 | value = func_wrapper(func_handle(std::move(func))); 81 | return true; 82 | } 83 | 84 | template 85 | static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) { 86 | if (!f_) 87 | return none().inc_ref(); 88 | 89 | auto result = f_.template target(); 90 | if (result) 91 | return cpp_function(*result, policy).release(); 92 | else 93 | return cpp_function(std::forward(f_), policy).release(); 94 | } 95 | 96 | PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster::name...) + _("], ") 97 | + make_caster::name + _("]")); 98 | }; 99 | 100 | NAMESPACE_END(detail) 101 | NAMESPACE_END(PYBIND11_NAMESPACE) 102 | -------------------------------------------------------------------------------- /plugin/pybind11/include/pybind11/options.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/options.h: global settings that are configurable at runtime. 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "detail/common.h" 13 | 14 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | 16 | class options { 17 | public: 18 | 19 | // Default RAII constructor, which leaves settings as they currently are. 20 | options() : previous_state(global_state()) {} 21 | 22 | // Class is non-copyable. 23 | options(const options&) = delete; 24 | options& operator=(const options&) = delete; 25 | 26 | // Destructor, which restores settings that were in effect before. 27 | ~options() { 28 | global_state() = previous_state; 29 | } 30 | 31 | // Setter methods (affect the global state): 32 | 33 | options& disable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = false; return *this; } 34 | 35 | options& enable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = true; return *this; } 36 | 37 | options& disable_function_signatures() & { global_state().show_function_signatures = false; return *this; } 38 | 39 | options& enable_function_signatures() & { global_state().show_function_signatures = true; return *this; } 40 | 41 | // Getter methods (return the global state): 42 | 43 | static bool show_user_defined_docstrings() { return global_state().show_user_defined_docstrings; } 44 | 45 | static bool show_function_signatures() { return global_state().show_function_signatures; } 46 | 47 | // This type is not meant to be allocated on the heap. 48 | void* operator new(size_t) = delete; 49 | 50 | private: 51 | 52 | struct state { 53 | bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings. 54 | bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings. 55 | }; 56 | 57 | static state &global_state() { 58 | static state instance; 59 | return instance; 60 | } 61 | 62 | state previous_state; 63 | }; 64 | 65 | NAMESPACE_END(PYBIND11_NAMESPACE) 66 | -------------------------------------------------------------------------------- /plugin/pybind11/pybind11/__init__.py: -------------------------------------------------------------------------------- 1 | from ._version import version_info, __version__ # noqa: F401 imported but unused 2 | 3 | 4 | def get_include(user=False): 5 | from distutils.dist import Distribution 6 | import os 7 | import sys 8 | 9 | # Are we running in a virtual environment? 10 | virtualenv = hasattr(sys, 'real_prefix') or \ 11 | sys.prefix != getattr(sys, "base_prefix", sys.prefix) 12 | 13 | # Are we running in a conda environment? 14 | conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta')) 15 | 16 | if virtualenv: 17 | return os.path.join(sys.prefix, 'include', 'site', 18 | 'python' + sys.version[:3]) 19 | elif conda: 20 | if os.name == 'nt': 21 | return os.path.join(sys.prefix, 'Library', 'include') 22 | else: 23 | return os.path.join(sys.prefix, 'include') 24 | else: 25 | dist = Distribution({'name': 'pybind11'}) 26 | dist.parse_config_files() 27 | 28 | dist_cobj = dist.get_command_obj('install', create=True) 29 | 30 | # Search for packages in user's home directory? 31 | if user: 32 | dist_cobj.user = user 33 | dist_cobj.prefix = "" 34 | dist_cobj.finalize_options() 35 | 36 | return os.path.dirname(dist_cobj.install_headers) 37 | -------------------------------------------------------------------------------- /plugin/pybind11/pybind11/__main__.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import argparse 4 | import sys 5 | import sysconfig 6 | 7 | from . import get_include 8 | 9 | 10 | def print_includes(): 11 | dirs = [sysconfig.get_path('include'), 12 | sysconfig.get_path('platinclude'), 13 | get_include(), 14 | get_include(True)] 15 | 16 | # Make unique but preserve order 17 | unique_dirs = [] 18 | for d in dirs: 19 | if d not in unique_dirs: 20 | unique_dirs.append(d) 21 | 22 | print(' '.join('-I' + d for d in unique_dirs)) 23 | 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser(prog='python -m pybind11') 27 | parser.add_argument('--includes', action='store_true', 28 | help='Include flags for both pybind11 and Python headers.') 29 | args = parser.parse_args() 30 | if not sys.argv[1:]: 31 | parser.print_help() 32 | if args.includes: 33 | print_includes() 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /plugin/pybind11/pybind11/_version.py: -------------------------------------------------------------------------------- 1 | version_info = (2, 3, 'dev1') 2 | __version__ = '.'.join(map(str, version_info)) 3 | -------------------------------------------------------------------------------- /plugin/pybind11/setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [flake8] 5 | max-line-length = 99 6 | show_source = True 7 | exclude = .git, __pycache__, build, dist, docs, tools, venv 8 | ignore = 9 | # required for pretty matrix formatting: multiple spaces after `,` and `[` 10 | E201, E241, W504, 11 | # camelcase 'cPickle' imported as lowercase 'pickle' 12 | N813 13 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/cross_module_gil_utils.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module 3 | 4 | Copyright (c) 2019 Google LLC 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | #include 10 | #include 11 | 12 | // This file mimics a DSO that makes pybind11 calls but does not define a 13 | // PYBIND11_MODULE. The purpose is to test that such a DSO can create a 14 | // py::gil_scoped_acquire when the running thread is in a GIL-released state. 15 | // 16 | // Note that we define a Python module here for convenience, but in general 17 | // this need not be the case. The typical scenario would be a DSO that implements 18 | // shared logic used internally by multiple pybind11 modules. 19 | 20 | namespace { 21 | 22 | namespace py = pybind11; 23 | void gil_acquire() { py::gil_scoped_acquire gil; } 24 | 25 | constexpr char kModuleName[] = "cross_module_gil_utils"; 26 | 27 | #if PY_MAJOR_VERSION >= 3 28 | struct PyModuleDef moduledef = { 29 | PyModuleDef_HEAD_INIT, 30 | kModuleName, 31 | NULL, 32 | 0, 33 | NULL, 34 | NULL, 35 | NULL, 36 | NULL, 37 | NULL 38 | }; 39 | #else 40 | PyMethodDef module_methods[] = { 41 | {NULL, NULL, 0, NULL} 42 | }; 43 | #endif 44 | 45 | } // namespace 46 | 47 | extern "C" PYBIND11_EXPORT 48 | #if PY_MAJOR_VERSION >= 3 49 | PyObject* PyInit_cross_module_gil_utils() 50 | #else 51 | void initcross_module_gil_utils() 52 | #endif 53 | { 54 | 55 | PyObject* m = 56 | #if PY_MAJOR_VERSION >= 3 57 | PyModule_Create(&moduledef); 58 | #else 59 | Py_InitModule(kModuleName, module_methods); 60 | #endif 61 | 62 | if (m != NULL) { 63 | static_assert( 64 | sizeof(&gil_acquire) == sizeof(void*), 65 | "Function pointer must have the same size as void*"); 66 | PyModule_AddObject(m, "gil_acquire_funcaddr", 67 | PyLong_FromVoidPtr(reinterpret_cast(&gil_acquire))); 68 | } 69 | 70 | #if PY_MAJOR_VERSION >= 3 71 | return m; 72 | #endif 73 | } 74 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/local_bindings.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pybind11_tests.h" 3 | 4 | /// Simple class used to test py::local: 5 | template class LocalBase { 6 | public: 7 | LocalBase(int i) : i(i) { } 8 | int i = -1; 9 | }; 10 | 11 | /// Registered with py::module_local in both main and secondary modules: 12 | using LocalType = LocalBase<0>; 13 | /// Registered without py::module_local in both modules: 14 | using NonLocalType = LocalBase<1>; 15 | /// A second non-local type (for stl_bind tests): 16 | using NonLocal2 = LocalBase<2>; 17 | /// Tests within-module, different-compilation-unit local definition conflict: 18 | using LocalExternal = LocalBase<3>; 19 | /// Mixed: registered local first, then global 20 | using MixedLocalGlobal = LocalBase<4>; 21 | /// Mixed: global first, then local 22 | using MixedGlobalLocal = LocalBase<5>; 23 | 24 | /// Registered with py::module_local only in the secondary module: 25 | using ExternalType1 = LocalBase<6>; 26 | using ExternalType2 = LocalBase<7>; 27 | 28 | using LocalVec = std::vector; 29 | using LocalVec2 = std::vector; 30 | using LocalMap = std::unordered_map; 31 | using NonLocalVec = std::vector; 32 | using NonLocalVec2 = std::vector; 33 | using NonLocalMap = std::unordered_map; 34 | using NonLocalMap2 = std::unordered_map; 35 | 36 | PYBIND11_MAKE_OPAQUE(LocalVec); 37 | PYBIND11_MAKE_OPAQUE(LocalVec2); 38 | PYBIND11_MAKE_OPAQUE(LocalMap); 39 | PYBIND11_MAKE_OPAQUE(NonLocalVec); 40 | //PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2 41 | PYBIND11_MAKE_OPAQUE(NonLocalMap); 42 | PYBIND11_MAKE_OPAQUE(NonLocalMap2); 43 | 44 | 45 | // Simple bindings (used with the above): 46 | template 47 | py::class_ bind_local(Args && ...args) { 48 | return py::class_(std::forward(args)...) 49 | .def(py::init()) 50 | .def("get", [](T &i) { return i.i + Adjust; }); 51 | }; 52 | 53 | // Simulate a foreign library base class (to match the example in the docs): 54 | namespace pets { 55 | class Pet { 56 | public: 57 | Pet(std::string name) : name_(name) {} 58 | std::string name_; 59 | const std::string &name() { return name_; } 60 | }; 61 | } 62 | 63 | struct MixGL { int i; MixGL(int i) : i{i} {} }; 64 | struct MixGL2 { int i; MixGL2(int i) : i{i} {} }; 65 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/pybind11_tests.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/pybind11_tests.cpp -- pybind example plugin 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include "constructor_stats.h" 12 | 13 | #include 14 | #include 15 | 16 | /* 17 | For testing purposes, we define a static global variable here in a function that each individual 18 | test .cpp calls with its initialization lambda. It's convenient here because we can just not 19 | compile some test files to disable/ignore some of the test code. 20 | 21 | It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will 22 | be essentially random, which is okay for our test scripts (there are no dependencies between the 23 | individual pybind11 test .cpp files), but most likely not what you want when using pybind11 24 | productively. 25 | 26 | Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions" 27 | section of the documentation for good practice on splitting binding code over multiple files. 28 | */ 29 | std::list> &initializers() { 30 | static std::list> inits; 31 | return inits; 32 | } 33 | 34 | test_initializer::test_initializer(Initializer init) { 35 | initializers().push_back(init); 36 | } 37 | 38 | test_initializer::test_initializer(const char *submodule_name, Initializer init) { 39 | initializers().push_back([=](py::module &parent) { 40 | auto m = parent.def_submodule(submodule_name); 41 | init(m); 42 | }); 43 | } 44 | 45 | void bind_ConstructorStats(py::module &m) { 46 | py::class_(m, "ConstructorStats") 47 | .def("alive", &ConstructorStats::alive) 48 | .def("values", &ConstructorStats::values) 49 | .def_readwrite("default_constructions", &ConstructorStats::default_constructions) 50 | .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments) 51 | .def_readwrite("move_assignments", &ConstructorStats::move_assignments) 52 | .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions) 53 | .def_readwrite("move_constructions", &ConstructorStats::move_constructions) 54 | .def_static("get", (ConstructorStats &(*)(py::object)) &ConstructorStats::get, py::return_value_policy::reference_internal) 55 | 56 | // Not exactly ConstructorStats, but related: expose the internal pybind number of registered instances 57 | // to allow instance cleanup checks (invokes a GC first) 58 | .def_static("detail_reg_inst", []() { 59 | ConstructorStats::gc(); 60 | return py::detail::get_internals().registered_instances.size(); 61 | }) 62 | ; 63 | } 64 | 65 | PYBIND11_MODULE(pybind11_tests, m) { 66 | m.doc() = "pybind11 test module"; 67 | 68 | bind_ConstructorStats(m); 69 | 70 | #if !defined(NDEBUG) 71 | m.attr("debug_enabled") = true; 72 | #else 73 | m.attr("debug_enabled") = false; 74 | #endif 75 | 76 | py::class_(m, "UserType", "A `py::class_` type for testing") 77 | .def(py::init<>()) 78 | .def(py::init()) 79 | .def("get_value", &UserType::value, "Get value using a method") 80 | .def("set_value", &UserType::set, "Set value using a method") 81 | .def_property("value", &UserType::value, &UserType::set, "Get/set value using a property") 82 | .def("__repr__", [](const UserType& u) { return "UserType({})"_s.format(u.value()); }); 83 | 84 | py::class_(m, "IncType") 85 | .def(py::init<>()) 86 | .def(py::init()) 87 | .def("__repr__", [](const IncType& u) { return "IncType({})"_s.format(u.value()); }); 88 | 89 | for (const auto &initializer : initializers()) 90 | initializer(m); 91 | 92 | if (!py::hasattr(m, "have_eigen")) m.attr("have_eigen") = false; 93 | } 94 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/pybind11_tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | #if defined(_MSC_VER) && _MSC_VER < 1910 5 | // We get some really long type names here which causes MSVC 2015 to emit warnings 6 | # pragma warning(disable: 4503) // warning C4503: decorated name length exceeded, name was truncated 7 | #endif 8 | 9 | namespace py = pybind11; 10 | using namespace pybind11::literals; 11 | 12 | class test_initializer { 13 | using Initializer = void (*)(py::module &); 14 | 15 | public: 16 | test_initializer(Initializer init); 17 | test_initializer(const char *submodule_name, Initializer init); 18 | }; 19 | 20 | #define TEST_SUBMODULE(name, variable) \ 21 | void test_submodule_##name(py::module &); \ 22 | test_initializer name(#name, test_submodule_##name); \ 23 | void test_submodule_##name(py::module &variable) 24 | 25 | 26 | /// Dummy type which is not exported anywhere -- something to trigger a conversion error 27 | struct UnregisteredType { }; 28 | 29 | /// A user-defined type which is exported and can be used by any test 30 | class UserType { 31 | public: 32 | UserType() = default; 33 | UserType(int i) : i(i) { } 34 | 35 | int value() const { return i; } 36 | void set(int set) { i = set; } 37 | 38 | private: 39 | int i = -1; 40 | }; 41 | 42 | /// Like UserType, but increments `value` on copy for quick reference vs. copy tests 43 | class IncType : public UserType { 44 | public: 45 | using UserType::UserType; 46 | IncType() = default; 47 | IncType(const IncType &other) : IncType(other.value() + 1) { } 48 | IncType(IncType &&) = delete; 49 | IncType &operator=(const IncType &) = delete; 50 | IncType &operator=(IncType &&) = delete; 51 | }; 52 | 53 | /// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast context. 54 | /// Used to test recursive casters (e.g. std::tuple, stl containers). 55 | struct RValueCaster {}; 56 | NAMESPACE_BEGIN(pybind11) 57 | NAMESPACE_BEGIN(detail) 58 | template<> class type_caster { 59 | public: 60 | PYBIND11_TYPE_CASTER(RValueCaster, _("RValueCaster")); 61 | static handle cast(RValueCaster &&, return_value_policy, handle) { return py::str("rvalue").release(); } 62 | static handle cast(const RValueCaster &, return_value_policy, handle) { return py::str("lvalue").release(); } 63 | }; 64 | NAMESPACE_END(detail) 65 | NAMESPACE_END(pybind11) 66 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | minversion = 3.0 3 | norecursedirs = test_cmake_build test_embed 4 | addopts = 5 | # show summary of skipped tests 6 | -rs 7 | # capture only Python print and C++ py::print, but not C output (low-level Python errors) 8 | --capture=sys 9 | filterwarnings = 10 | # make warnings into errors but ignore certain third-party extension issues 11 | error 12 | # importing scipy submodules on some version of Python 13 | ignore::ImportWarning 14 | # bogus numpy ABI warning (see numpy/#432) 15 | ignore:.*numpy.dtype size changed.*:RuntimeWarning 16 | ignore:.*numpy.ufunc size changed.*:RuntimeWarning 17 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_async.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_async.cpp -- __await__ support 3 | 4 | Copyright (c) 2019 Google Inc. 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(async_module, m) { 13 | struct DoesNotSupportAsync {}; 14 | py::class_(m, "DoesNotSupportAsync") 15 | .def(py::init<>()); 16 | struct SupportsAsync {}; 17 | py::class_(m, "SupportsAsync") 18 | .def(py::init<>()) 19 | .def("__await__", [](const SupportsAsync& self) -> py::object { 20 | static_cast(self); 21 | py::object loop = py::module::import("asyncio.events").attr("get_event_loop")(); 22 | py::object f = loop.attr("create_future")(); 23 | f.attr("set_result")(5); 24 | return f.attr("__await__")(); 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_async.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import pytest 3 | from pybind11_tests import async_module as m 4 | 5 | 6 | @pytest.fixture 7 | def event_loop(): 8 | loop = asyncio.new_event_loop() 9 | yield loop 10 | loop.close() 11 | 12 | 13 | async def get_await_result(x): 14 | return await x 15 | 16 | 17 | def test_await(event_loop): 18 | assert 5 == event_loop.run_until_complete(get_await_result(m.SupportsAsync())) 19 | 20 | 21 | def test_await_missing(event_loop): 22 | with pytest.raises(TypeError): 23 | event_loop.run_until_complete(get_await_result(m.DoesNotSupportAsync())) 24 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_buffers.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import pytest 3 | from pybind11_tests import buffers as m 4 | from pybind11_tests import ConstructorStats 5 | 6 | pytestmark = pytest.requires_numpy 7 | 8 | with pytest.suppress(ImportError): 9 | import numpy as np 10 | 11 | 12 | def test_from_python(): 13 | with pytest.raises(RuntimeError) as excinfo: 14 | m.Matrix(np.array([1, 2, 3])) # trying to assign a 1D array 15 | assert str(excinfo.value) == "Incompatible buffer format!" 16 | 17 | m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32) 18 | m4 = m.Matrix(m3) 19 | 20 | for i in range(m4.rows()): 21 | for j in range(m4.cols()): 22 | assert m3[i, j] == m4[i, j] 23 | 24 | cstats = ConstructorStats.get(m.Matrix) 25 | assert cstats.alive() == 1 26 | del m3, m4 27 | assert cstats.alive() == 0 28 | assert cstats.values() == ["2x3 matrix"] 29 | assert cstats.copy_constructions == 0 30 | # assert cstats.move_constructions >= 0 # Don't invoke any 31 | assert cstats.copy_assignments == 0 32 | assert cstats.move_assignments == 0 33 | 34 | 35 | # PyPy: Memory leak in the "np.array(m, copy=False)" call 36 | # https://bitbucket.org/pypy/pypy/issues/2444 37 | @pytest.unsupported_on_pypy 38 | def test_to_python(): 39 | mat = m.Matrix(5, 4) 40 | assert memoryview(mat).shape == (5, 4) 41 | 42 | assert mat[2, 3] == 0 43 | mat[2, 3] = 4.0 44 | mat[3, 2] = 7.0 45 | assert mat[2, 3] == 4 46 | assert mat[3, 2] == 7 47 | assert struct.unpack_from('f', mat, (3 * 4 + 2) * 4) == (7, ) 48 | assert struct.unpack_from('f', mat, (2 * 4 + 3) * 4) == (4, ) 49 | 50 | mat2 = np.array(mat, copy=False) 51 | assert mat2.shape == (5, 4) 52 | assert abs(mat2).sum() == 11 53 | assert mat2[2, 3] == 4 and mat2[3, 2] == 7 54 | mat2[2, 3] = 5 55 | assert mat2[2, 3] == 5 56 | 57 | cstats = ConstructorStats.get(m.Matrix) 58 | assert cstats.alive() == 1 59 | del mat 60 | pytest.gc_collect() 61 | assert cstats.alive() == 1 62 | del mat2 # holds a mat reference 63 | pytest.gc_collect() 64 | assert cstats.alive() == 0 65 | assert cstats.values() == ["5x4 matrix"] 66 | assert cstats.copy_constructions == 0 67 | # assert cstats.move_constructions >= 0 # Don't invoke any 68 | assert cstats.copy_assignments == 0 69 | assert cstats.move_assignments == 0 70 | 71 | 72 | @pytest.unsupported_on_pypy 73 | def test_inherited_protocol(): 74 | """SquareMatrix is derived from Matrix and inherits the buffer protocol""" 75 | 76 | matrix = m.SquareMatrix(5) 77 | assert memoryview(matrix).shape == (5, 5) 78 | assert np.asarray(matrix).shape == (5, 5) 79 | 80 | 81 | @pytest.unsupported_on_pypy 82 | def test_pointer_to_member_fn(): 83 | for cls in [m.Buffer, m.ConstBuffer, m.DerivedBuffer]: 84 | buf = cls() 85 | buf.value = 0x12345678 86 | value = struct.unpack('i', bytearray(buf))[0] 87 | assert value == 0x12345678 88 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_call_policies.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_call_policies.cpp -- keep_alive and call_guard 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | struct CustomGuard { 13 | static bool enabled; 14 | 15 | CustomGuard() { enabled = true; } 16 | ~CustomGuard() { enabled = false; } 17 | 18 | static const char *report_status() { return enabled ? "guarded" : "unguarded"; } 19 | }; 20 | bool CustomGuard::enabled = false; 21 | 22 | struct DependentGuard { 23 | static bool enabled; 24 | 25 | DependentGuard() { enabled = CustomGuard::enabled; } 26 | ~DependentGuard() { enabled = false; } 27 | 28 | static const char *report_status() { return enabled ? "guarded" : "unguarded"; } 29 | }; 30 | bool DependentGuard::enabled = false; 31 | 32 | TEST_SUBMODULE(call_policies, m) { 33 | // Parent/Child are used in: 34 | // test_keep_alive_argument, test_keep_alive_return_value, test_alive_gc_derived, 35 | // test_alive_gc_multi_derived, test_return_none, test_keep_alive_constructor 36 | class Child { 37 | public: 38 | Child() { py::print("Allocating child."); } 39 | Child(const Child &) = default; 40 | Child(Child &&) = default; 41 | ~Child() { py::print("Releasing child."); } 42 | }; 43 | py::class_(m, "Child") 44 | .def(py::init<>()); 45 | 46 | class Parent { 47 | public: 48 | Parent() { py::print("Allocating parent."); } 49 | ~Parent() { py::print("Releasing parent."); } 50 | void addChild(Child *) { } 51 | Child *returnChild() { return new Child(); } 52 | Child *returnNullChild() { return nullptr; } 53 | }; 54 | py::class_(m, "Parent") 55 | .def(py::init<>()) 56 | .def(py::init([](Child *) { return new Parent(); }), py::keep_alive<1, 2>()) 57 | .def("addChild", &Parent::addChild) 58 | .def("addChildKeepAlive", &Parent::addChild, py::keep_alive<1, 2>()) 59 | .def("returnChild", &Parent::returnChild) 60 | .def("returnChildKeepAlive", &Parent::returnChild, py::keep_alive<1, 0>()) 61 | .def("returnNullChildKeepAliveChild", &Parent::returnNullChild, py::keep_alive<1, 0>()) 62 | .def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>()); 63 | 64 | #if !defined(PYPY_VERSION) 65 | // test_alive_gc 66 | class ParentGC : public Parent { 67 | public: 68 | using Parent::Parent; 69 | }; 70 | py::class_(m, "ParentGC", py::dynamic_attr()) 71 | .def(py::init<>()); 72 | #endif 73 | 74 | // test_call_guard 75 | m.def("unguarded_call", &CustomGuard::report_status); 76 | m.def("guarded_call", &CustomGuard::report_status, py::call_guard()); 77 | 78 | m.def("multiple_guards_correct_order", []() { 79 | return CustomGuard::report_status() + std::string(" & ") + DependentGuard::report_status(); 80 | }, py::call_guard()); 81 | 82 | m.def("multiple_guards_wrong_order", []() { 83 | return DependentGuard::report_status() + std::string(" & ") + CustomGuard::report_status(); 84 | }, py::call_guard()); 85 | 86 | #if defined(WITH_THREAD) && !defined(PYPY_VERSION) 87 | // `py::call_guard()` should work in PyPy as well, 88 | // but it's unclear how to test it without `PyGILState_GetThisThreadState`. 89 | auto report_gil_status = []() { 90 | auto is_gil_held = false; 91 | if (auto tstate = py::detail::get_thread_state_unchecked()) 92 | is_gil_held = (tstate == PyGILState_GetThisThreadState()); 93 | 94 | return is_gil_held ? "GIL held" : "GIL released"; 95 | }; 96 | 97 | m.def("with_gil", report_gil_status); 98 | m.def("without_gil", report_gil_status, py::call_guard()); 99 | #endif 100 | } 101 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_chrono.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_chrono.cpp -- test conversions to/from std::chrono types 3 | 4 | Copyright (c) 2016 Trent Houliston and 5 | Wenzel Jakob 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include 13 | 14 | TEST_SUBMODULE(chrono, m) { 15 | using system_time = std::chrono::system_clock::time_point; 16 | using steady_time = std::chrono::steady_clock::time_point; 17 | 18 | using timespan = std::chrono::duration; 19 | using timestamp = std::chrono::time_point; 20 | 21 | // test_chrono_system_clock 22 | // Return the current time off the wall clock 23 | m.def("test_chrono1", []() { return std::chrono::system_clock::now(); }); 24 | 25 | // test_chrono_system_clock_roundtrip 26 | // Round trip the passed in system clock time 27 | m.def("test_chrono2", [](system_time t) { return t; }); 28 | 29 | // test_chrono_duration_roundtrip 30 | // Round trip the passed in duration 31 | m.def("test_chrono3", [](std::chrono::system_clock::duration d) { return d; }); 32 | 33 | // test_chrono_duration_subtraction_equivalence 34 | // Difference between two passed in time_points 35 | m.def("test_chrono4", [](system_time a, system_time b) { return a - b; }); 36 | 37 | // test_chrono_steady_clock 38 | // Return the current time off the steady_clock 39 | m.def("test_chrono5", []() { return std::chrono::steady_clock::now(); }); 40 | 41 | // test_chrono_steady_clock_roundtrip 42 | // Round trip a steady clock timepoint 43 | m.def("test_chrono6", [](steady_time t) { return t; }); 44 | 45 | // test_floating_point_duration 46 | // Roundtrip a duration in microseconds from a float argument 47 | m.def("test_chrono7", [](std::chrono::microseconds t) { return t; }); 48 | // Float durations (issue #719) 49 | m.def("test_chrono_float_diff", [](std::chrono::duration a, std::chrono::duration b) { 50 | return a - b; }); 51 | 52 | m.def("test_nano_timepoint", [](timestamp start, timespan delta) -> timestamp { 53 | return start + delta; 54 | }); 55 | } 56 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_custom_target(test_cmake_build) 2 | 3 | if(CMAKE_VERSION VERSION_LESS 3.1) 4 | # 3.0 needed for interface library for subdirectory_target/installed_target 5 | # 3.1 needed for cmake -E env for testing 6 | return() 7 | endif() 8 | 9 | include(CMakeParseArguments) 10 | function(pybind11_add_build_test name) 11 | cmake_parse_arguments(ARG "INSTALL" "" "" ${ARGN}) 12 | 13 | set(build_options "-DCMAKE_PREFIX_PATH=${PROJECT_BINARY_DIR}/mock_install" 14 | "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}" 15 | "-DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE}" 16 | "-DPYBIND11_CPP_STANDARD=${PYBIND11_CPP_STANDARD}") 17 | if(NOT ARG_INSTALL) 18 | list(APPEND build_options "-DPYBIND11_PROJECT_DIR=${PROJECT_SOURCE_DIR}") 19 | endif() 20 | 21 | add_custom_target(test_${name} ${CMAKE_CTEST_COMMAND} 22 | --quiet --output-log ${name}.log 23 | --build-and-test "${CMAKE_CURRENT_SOURCE_DIR}/${name}" 24 | "${CMAKE_CURRENT_BINARY_DIR}/${name}" 25 | --build-config Release 26 | --build-noclean 27 | --build-generator ${CMAKE_GENERATOR} 28 | $<$:--build-generator-platform> ${CMAKE_GENERATOR_PLATFORM} 29 | --build-makeprogram ${CMAKE_MAKE_PROGRAM} 30 | --build-target check 31 | --build-options ${build_options} 32 | ) 33 | if(ARG_INSTALL) 34 | add_dependencies(test_${name} mock_install) 35 | endif() 36 | add_dependencies(test_cmake_build test_${name}) 37 | endfunction() 38 | 39 | pybind11_add_build_test(subdirectory_function) 40 | pybind11_add_build_test(subdirectory_target) 41 | if(NOT ${PYTHON_MODULE_EXTENSION} MATCHES "pypy") 42 | pybind11_add_build_test(subdirectory_embed) 43 | endif() 44 | 45 | if(PYBIND11_INSTALL) 46 | add_custom_target(mock_install ${CMAKE_COMMAND} 47 | "-DCMAKE_INSTALL_PREFIX=${PROJECT_BINARY_DIR}/mock_install" 48 | -P "${PROJECT_BINARY_DIR}/cmake_install.cmake" 49 | ) 50 | 51 | pybind11_add_build_test(installed_function INSTALL) 52 | pybind11_add_build_test(installed_target INSTALL) 53 | if(NOT ${PYTHON_MODULE_EXTENSION} MATCHES "pypy") 54 | pybind11_add_build_test(installed_embed INSTALL) 55 | endif() 56 | endif() 57 | 58 | add_dependencies(check test_cmake_build) 59 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/embed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | namespace py = pybind11; 3 | 4 | PYBIND11_EMBEDDED_MODULE(test_cmake_build, m) { 5 | m.def("add", [](int i, int j) { return i + j; }); 6 | } 7 | 8 | int main(int argc, char *argv[]) { 9 | if (argc != 2) 10 | throw std::runtime_error("Expected test.py file as the first argument"); 11 | auto test_py_file = argv[1]; 12 | 13 | py::scoped_interpreter guard{}; 14 | 15 | auto m = py::module::import("test_cmake_build"); 16 | if (m.attr("add")(1, 2).cast() != 3) 17 | throw std::runtime_error("embed.cpp failed"); 18 | 19 | py::module::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp"); 20 | py::eval_file(test_py_file, py::globals()); 21 | } 22 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/installed_embed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_installed_embed CXX) 3 | 4 | set(CMAKE_MODULE_PATH "") 5 | find_package(pybind11 CONFIG REQUIRED) 6 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 7 | 8 | add_executable(test_cmake_build ../embed.cpp) 9 | target_link_libraries(test_cmake_build PRIVATE pybind11::embed) 10 | 11 | # Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::embed). 12 | # This may be needed to resolve header conflicts, e.g. between Python release and debug headers. 13 | set_target_properties(test_cmake_build PROPERTIES NO_SYSTEM_FROM_IMPORTED ON) 14 | 15 | add_custom_target(check $ ${PROJECT_SOURCE_DIR}/../test.py) 16 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/installed_function/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.12) 2 | project(test_installed_module CXX) 3 | 4 | set(CMAKE_MODULE_PATH "") 5 | 6 | find_package(pybind11 CONFIG REQUIRED) 7 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 8 | 9 | pybind11_add_module(test_cmake_build SHARED NO_EXTRAS ../main.cpp) 10 | 11 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 12 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 13 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/installed_target/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_installed_target CXX) 3 | 4 | set(CMAKE_MODULE_PATH "") 5 | 6 | find_package(pybind11 CONFIG REQUIRED) 7 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 8 | 9 | add_library(test_cmake_build MODULE ../main.cpp) 10 | 11 | target_link_libraries(test_cmake_build PRIVATE pybind11::module) 12 | 13 | # make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib 14 | set_target_properties(test_cmake_build PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}" 15 | SUFFIX "${PYTHON_MODULE_EXTENSION}") 16 | 17 | # Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::module). 18 | # This may be needed to resolve header conflicts, e.g. between Python release and debug headers. 19 | set_target_properties(test_cmake_build PROPERTIES NO_SYSTEM_FROM_IMPORTED ON) 20 | 21 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 22 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 23 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | namespace py = pybind11; 3 | 4 | PYBIND11_MODULE(test_cmake_build, m) { 5 | m.def("add", [](int i, int j) { return i + j; }); 6 | } 7 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_subdirectory_embed CXX) 3 | 4 | set(PYBIND11_INSTALL ON CACHE BOOL "") 5 | set(PYBIND11_EXPORT_NAME test_export) 6 | 7 | add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) 8 | 9 | # Test basic target functionality 10 | add_executable(test_cmake_build ../embed.cpp) 11 | target_link_libraries(test_cmake_build PRIVATE pybind11::embed) 12 | 13 | add_custom_target(check $ ${PROJECT_SOURCE_DIR}/../test.py) 14 | 15 | # Test custom export group -- PYBIND11_EXPORT_NAME 16 | add_library(test_embed_lib ../embed.cpp) 17 | target_link_libraries(test_embed_lib PRIVATE pybind11::embed) 18 | 19 | install(TARGETS test_embed_lib 20 | EXPORT test_export 21 | ARCHIVE DESTINATION bin 22 | LIBRARY DESTINATION lib 23 | RUNTIME DESTINATION lib) 24 | install(EXPORT test_export 25 | DESTINATION lib/cmake/test_export/test_export-Targets.cmake) 26 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/subdirectory_function/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.12) 2 | project(test_subdirectory_module CXX) 3 | 4 | add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) 5 | pybind11_add_module(test_cmake_build THIN_LTO ../main.cpp) 6 | 7 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 8 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 9 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/subdirectory_target/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_subdirectory_target CXX) 3 | 4 | add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) 5 | 6 | add_library(test_cmake_build MODULE ../main.cpp) 7 | 8 | target_link_libraries(test_cmake_build PRIVATE pybind11::module) 9 | 10 | # make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib 11 | set_target_properties(test_cmake_build PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}" 12 | SUFFIX "${PYTHON_MODULE_EXTENSION}") 13 | 14 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 15 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 16 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_cmake_build/test.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import test_cmake_build 3 | 4 | assert test_cmake_build.add(1, 2) == 3 5 | print("{} imports, runs, and adds: 1 + 2 = 3".format(sys.argv[1])) 6 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_constants_and_functions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw byte strings 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | enum MyEnum { EFirstEntry = 1, ESecondEntry }; 13 | 14 | std::string test_function1() { 15 | return "test_function()"; 16 | } 17 | 18 | std::string test_function2(MyEnum k) { 19 | return "test_function(enum=" + std::to_string(k) + ")"; 20 | } 21 | 22 | std::string test_function3(int i) { 23 | return "test_function(" + std::to_string(i) + ")"; 24 | } 25 | 26 | py::str test_function4() { return "test_function()"; } 27 | py::str test_function4(char *) { return "test_function(char *)"; } 28 | py::str test_function4(int, float) { return "test_function(int, float)"; } 29 | py::str test_function4(float, int) { return "test_function(float, int)"; } 30 | 31 | py::bytes return_bytes() { 32 | const char *data = "\x01\x00\x02\x00"; 33 | return std::string(data, 4); 34 | } 35 | 36 | std::string print_bytes(py::bytes bytes) { 37 | std::string ret = "bytes["; 38 | const auto value = static_cast(bytes); 39 | for (size_t i = 0; i < value.length(); ++i) { 40 | ret += std::to_string(static_cast(value[i])) + " "; 41 | } 42 | ret.back() = ']'; 43 | return ret; 44 | } 45 | 46 | // Test that we properly handle C++17 exception specifiers (which are part of the function signature 47 | // in C++17). These should all still work before C++17, but don't affect the function signature. 48 | namespace test_exc_sp { 49 | int f1(int x) noexcept { return x+1; } 50 | int f2(int x) noexcept(true) { return x+2; } 51 | int f3(int x) noexcept(false) { return x+3; } 52 | #if defined(__GNUG__) 53 | # pragma GCC diagnostic push 54 | # pragma GCC diagnostic ignored "-Wdeprecated" 55 | #endif 56 | int f4(int x) throw() { return x+4; } // Deprecated equivalent to noexcept(true) 57 | #if defined(__GNUG__) 58 | # pragma GCC diagnostic pop 59 | #endif 60 | struct C { 61 | int m1(int x) noexcept { return x-1; } 62 | int m2(int x) const noexcept { return x-2; } 63 | int m3(int x) noexcept(true) { return x-3; } 64 | int m4(int x) const noexcept(true) { return x-4; } 65 | int m5(int x) noexcept(false) { return x-5; } 66 | int m6(int x) const noexcept(false) { return x-6; } 67 | #if defined(__GNUG__) 68 | # pragma GCC diagnostic push 69 | # pragma GCC diagnostic ignored "-Wdeprecated" 70 | #endif 71 | int m7(int x) throw() { return x-7; } 72 | int m8(int x) const throw() { return x-8; } 73 | #if defined(__GNUG__) 74 | # pragma GCC diagnostic pop 75 | #endif 76 | }; 77 | } 78 | 79 | 80 | TEST_SUBMODULE(constants_and_functions, m) { 81 | // test_constants 82 | m.attr("some_constant") = py::int_(14); 83 | 84 | // test_function_overloading 85 | m.def("test_function", &test_function1); 86 | m.def("test_function", &test_function2); 87 | m.def("test_function", &test_function3); 88 | 89 | #if defined(PYBIND11_OVERLOAD_CAST) 90 | m.def("test_function", py::overload_cast<>(&test_function4)); 91 | m.def("test_function", py::overload_cast(&test_function4)); 92 | m.def("test_function", py::overload_cast(&test_function4)); 93 | m.def("test_function", py::overload_cast(&test_function4)); 94 | #else 95 | m.def("test_function", static_cast(&test_function4)); 96 | m.def("test_function", static_cast(&test_function4)); 97 | m.def("test_function", static_cast(&test_function4)); 98 | m.def("test_function", static_cast(&test_function4)); 99 | #endif 100 | 101 | py::enum_(m, "MyEnum") 102 | .value("EFirstEntry", EFirstEntry) 103 | .value("ESecondEntry", ESecondEntry) 104 | .export_values(); 105 | 106 | // test_bytes 107 | m.def("return_bytes", &return_bytes); 108 | m.def("print_bytes", &print_bytes); 109 | 110 | // test_exception_specifiers 111 | using namespace test_exc_sp; 112 | py::class_(m, "C") 113 | .def(py::init<>()) 114 | .def("m1", &C::m1) 115 | .def("m2", &C::m2) 116 | .def("m3", &C::m3) 117 | .def("m4", &C::m4) 118 | .def("m5", &C::m5) 119 | .def("m6", &C::m6) 120 | .def("m7", &C::m7) 121 | .def("m8", &C::m8) 122 | ; 123 | m.def("f1", f1); 124 | m.def("f2", f2); 125 | m.def("f3", f3); 126 | m.def("f4", f4); 127 | } 128 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_constants_and_functions.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import constants_and_functions as m 2 | 3 | 4 | def test_constants(): 5 | assert m.some_constant == 14 6 | 7 | 8 | def test_function_overloading(): 9 | assert m.test_function() == "test_function()" 10 | assert m.test_function(7) == "test_function(7)" 11 | assert m.test_function(m.MyEnum.EFirstEntry) == "test_function(enum=1)" 12 | assert m.test_function(m.MyEnum.ESecondEntry) == "test_function(enum=2)" 13 | 14 | assert m.test_function() == "test_function()" 15 | assert m.test_function("abcd") == "test_function(char *)" 16 | assert m.test_function(1, 1.0) == "test_function(int, float)" 17 | assert m.test_function(1, 1.0) == "test_function(int, float)" 18 | assert m.test_function(2.0, 2) == "test_function(float, int)" 19 | 20 | 21 | def test_bytes(): 22 | assert m.print_bytes(m.return_bytes()) == "bytes[1 0 2 0]" 23 | 24 | 25 | def test_exception_specifiers(): 26 | c = m.C() 27 | assert c.m1(2) == 1 28 | assert c.m2(3) == 1 29 | assert c.m3(5) == 2 30 | assert c.m4(7) == 3 31 | assert c.m5(10) == 5 32 | assert c.m6(14) == 8 33 | assert c.m7(20) == 13 34 | assert c.m8(29) == 21 35 | 36 | assert m.f1(33) == 34 37 | assert m.f2(53) == 55 38 | assert m.f3(86) == 89 39 | assert m.f4(140) == 144 40 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_docstring_options.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_docstring_options.cpp -- generation of docstrings and signatures 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(docstring_options, m) { 13 | // test_docstring_options 14 | { 15 | py::options options; 16 | options.disable_function_signatures(); 17 | 18 | m.def("test_function1", [](int, int) {}, py::arg("a"), py::arg("b")); 19 | m.def("test_function2", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 20 | 21 | m.def("test_overloaded1", [](int) {}, py::arg("i"), "Overload docstring"); 22 | m.def("test_overloaded1", [](double) {}, py::arg("d")); 23 | 24 | m.def("test_overloaded2", [](int) {}, py::arg("i"), "overload docstring 1"); 25 | m.def("test_overloaded2", [](double) {}, py::arg("d"), "overload docstring 2"); 26 | 27 | m.def("test_overloaded3", [](int) {}, py::arg("i")); 28 | m.def("test_overloaded3", [](double) {}, py::arg("d"), "Overload docstr"); 29 | 30 | options.enable_function_signatures(); 31 | 32 | m.def("test_function3", [](int, int) {}, py::arg("a"), py::arg("b")); 33 | m.def("test_function4", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 34 | 35 | options.disable_function_signatures().disable_user_defined_docstrings(); 36 | 37 | m.def("test_function5", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 38 | 39 | { 40 | py::options nested_options; 41 | nested_options.enable_user_defined_docstrings(); 42 | m.def("test_function6", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 43 | } 44 | } 45 | 46 | m.def("test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 47 | 48 | { 49 | py::options options; 50 | options.disable_user_defined_docstrings(); 51 | 52 | struct DocstringTestFoo { 53 | int value; 54 | void setValue(int v) { value = v; } 55 | int getValue() const { return value; } 56 | }; 57 | py::class_(m, "DocstringTestFoo", "This is a class docstring") 58 | .def_property("value_prop", &DocstringTestFoo::getValue, &DocstringTestFoo::setValue, "This is a property docstring") 59 | ; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_docstring_options.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import docstring_options as m 2 | 3 | 4 | def test_docstring_options(): 5 | # options.disable_function_signatures() 6 | assert not m.test_function1.__doc__ 7 | 8 | assert m.test_function2.__doc__ == "A custom docstring" 9 | 10 | # docstring specified on just the first overload definition: 11 | assert m.test_overloaded1.__doc__ == "Overload docstring" 12 | 13 | # docstring on both overloads: 14 | assert m.test_overloaded2.__doc__ == "overload docstring 1\noverload docstring 2" 15 | 16 | # docstring on only second overload: 17 | assert m.test_overloaded3.__doc__ == "Overload docstr" 18 | 19 | # options.enable_function_signatures() 20 | assert m.test_function3.__doc__ .startswith("test_function3(a: int, b: int) -> None") 21 | 22 | assert m.test_function4.__doc__ .startswith("test_function4(a: int, b: int) -> None") 23 | assert m.test_function4.__doc__ .endswith("A custom docstring\n") 24 | 25 | # options.disable_function_signatures() 26 | # options.disable_user_defined_docstrings() 27 | assert not m.test_function5.__doc__ 28 | 29 | # nested options.enable_user_defined_docstrings() 30 | assert m.test_function6.__doc__ == "A custom docstring" 31 | 32 | # RAII destructor 33 | assert m.test_function7.__doc__ .startswith("test_function7(a: int, b: int) -> None") 34 | assert m.test_function7.__doc__ .endswith("A custom docstring\n") 35 | 36 | # Suppression of user-defined docstrings for non-function objects 37 | assert not m.DocstringTestFoo.__doc__ 38 | assert not m.DocstringTestFoo.value_prop.__doc__ 39 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_embed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | if(${PYTHON_MODULE_EXTENSION} MATCHES "pypy") 2 | add_custom_target(cpptest) # Dummy target on PyPy. Embedding is not supported. 3 | set(_suppress_unused_variable_warning "${DOWNLOAD_CATCH}") 4 | return() 5 | endif() 6 | 7 | find_package(Catch 1.9.3) 8 | if(CATCH_FOUND) 9 | message(STATUS "Building interpreter tests using Catch v${CATCH_VERSION}") 10 | else() 11 | message(STATUS "Catch not detected. Interpreter tests will be skipped. Install Catch headers" 12 | " manually or use `cmake -DDOWNLOAD_CATCH=1` to fetch them automatically.") 13 | return() 14 | endif() 15 | 16 | add_executable(test_embed 17 | catch.cpp 18 | test_interpreter.cpp 19 | ) 20 | target_include_directories(test_embed PRIVATE ${CATCH_INCLUDE_DIR}) 21 | pybind11_enable_warnings(test_embed) 22 | 23 | if(NOT CMAKE_VERSION VERSION_LESS 3.0) 24 | target_link_libraries(test_embed PRIVATE pybind11::embed) 25 | else() 26 | target_include_directories(test_embed PRIVATE ${PYBIND11_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS}) 27 | target_compile_options(test_embed PRIVATE ${PYBIND11_CPP_STANDARD}) 28 | target_link_libraries(test_embed PRIVATE ${PYTHON_LIBRARIES}) 29 | endif() 30 | 31 | find_package(Threads REQUIRED) 32 | target_link_libraries(test_embed PUBLIC ${CMAKE_THREAD_LIBS_INIT}) 33 | 34 | add_custom_target(cpptest COMMAND $ 35 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) 36 | 37 | pybind11_add_module(external_module THIN_LTO external_module.cpp) 38 | set_target_properties(external_module PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) 39 | add_dependencies(cpptest external_module) 40 | 41 | add_dependencies(check cpptest) 42 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_embed/catch.cpp: -------------------------------------------------------------------------------- 1 | // The Catch implementation is compiled here. This is a standalone 2 | // translation unit to avoid recompiling it for every test change. 3 | 4 | #include 5 | 6 | #ifdef _MSC_VER 7 | // Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to catch 8 | // 2.0.1; this should be fixed in the next catch release after 2.0.1). 9 | # pragma warning(disable: 4996) 10 | #endif 11 | 12 | #define CATCH_CONFIG_RUNNER 13 | #include 14 | 15 | namespace py = pybind11; 16 | 17 | int main(int argc, char *argv[]) { 18 | py::scoped_interpreter guard{}; 19 | auto result = Catch::Session().run(argc, argv); 20 | 21 | return result < 0xff ? result : 0xff; 22 | } 23 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_embed/external_module.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace py = pybind11; 4 | 5 | /* Simple test module/test class to check that the referenced internals data of external pybind11 6 | * modules aren't preserved over a finalize/initialize. 7 | */ 8 | 9 | PYBIND11_MODULE(external_module, m) { 10 | class A { 11 | public: 12 | A(int value) : v{value} {}; 13 | int v; 14 | }; 15 | 16 | py::class_(m, "A") 17 | .def(py::init()) 18 | .def_readwrite("value", &A::v); 19 | 20 | m.def("internals_at", []() { 21 | return reinterpret_cast(&py::detail::get_internals()); 22 | }); 23 | } 24 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_embed/test_interpreter.py: -------------------------------------------------------------------------------- 1 | from widget_module import Widget 2 | 3 | 4 | class DerivedWidget(Widget): 5 | def __init__(self, message): 6 | super(DerivedWidget, self).__init__(message) 7 | 8 | def the_answer(self): 9 | return 42 10 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_enum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_enums.cpp -- enumerations 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(enums, m) { 13 | // test_unscoped_enum 14 | enum UnscopedEnum { 15 | EOne = 1, 16 | ETwo 17 | }; 18 | py::enum_(m, "UnscopedEnum", py::arithmetic(), "An unscoped enumeration") 19 | .value("EOne", EOne, "Docstring for EOne") 20 | .value("ETwo", ETwo, "Docstring for ETwo") 21 | .export_values(); 22 | 23 | // test_scoped_enum 24 | enum class ScopedEnum { 25 | Two = 2, 26 | Three 27 | }; 28 | py::enum_(m, "ScopedEnum", py::arithmetic()) 29 | .value("Two", ScopedEnum::Two) 30 | .value("Three", ScopedEnum::Three); 31 | 32 | m.def("test_scoped_enum", [](ScopedEnum z) { 33 | return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three"); 34 | }); 35 | 36 | // test_binary_operators 37 | enum Flags { 38 | Read = 4, 39 | Write = 2, 40 | Execute = 1 41 | }; 42 | py::enum_(m, "Flags", py::arithmetic()) 43 | .value("Read", Flags::Read) 44 | .value("Write", Flags::Write) 45 | .value("Execute", Flags::Execute) 46 | .export_values(); 47 | 48 | // test_implicit_conversion 49 | class ClassWithUnscopedEnum { 50 | public: 51 | enum EMode { 52 | EFirstMode = 1, 53 | ESecondMode 54 | }; 55 | 56 | static EMode test_function(EMode mode) { 57 | return mode; 58 | } 59 | }; 60 | py::class_ exenum_class(m, "ClassWithUnscopedEnum"); 61 | exenum_class.def_static("test_function", &ClassWithUnscopedEnum::test_function); 62 | py::enum_(exenum_class, "EMode") 63 | .value("EFirstMode", ClassWithUnscopedEnum::EFirstMode) 64 | .value("ESecondMode", ClassWithUnscopedEnum::ESecondMode) 65 | .export_values(); 66 | 67 | // test_enum_to_int 68 | m.def("test_enum_to_int", [](int) { }); 69 | m.def("test_enum_to_uint", [](uint32_t) { }); 70 | m.def("test_enum_to_long_long", [](long long) { }); 71 | 72 | // test_duplicate_enum_name 73 | enum SimpleEnum 74 | { 75 | ONE, TWO, THREE 76 | }; 77 | 78 | m.def("register_bad_enum", [m]() { 79 | py::enum_(m, "SimpleEnum") 80 | .value("ONE", SimpleEnum::ONE) //NOTE: all value function calls are called with the same first parameter value 81 | .value("ONE", SimpleEnum::TWO) 82 | .value("ONE", SimpleEnum::THREE) 83 | .export_values(); 84 | }); 85 | } 86 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_eval.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_eval.cpp -- Usage of eval() and eval_file() 3 | 4 | Copyright (c) 2016 Klemens D. Morgenstern 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | 11 | #include 12 | #include "pybind11_tests.h" 13 | 14 | TEST_SUBMODULE(eval_, m) { 15 | // test_evals 16 | 17 | auto global = py::dict(py::module::import("__main__").attr("__dict__")); 18 | 19 | m.def("test_eval_statements", [global]() { 20 | auto local = py::dict(); 21 | local["call_test"] = py::cpp_function([&]() -> int { 22 | return 42; 23 | }); 24 | 25 | // Regular string literal 26 | py::exec( 27 | "message = 'Hello World!'\n" 28 | "x = call_test()", 29 | global, local 30 | ); 31 | 32 | // Multi-line raw string literal 33 | py::exec(R"( 34 | if x == 42: 35 | print(message) 36 | else: 37 | raise RuntimeError 38 | )", global, local 39 | ); 40 | auto x = local["x"].cast(); 41 | 42 | return x == 42; 43 | }); 44 | 45 | m.def("test_eval", [global]() { 46 | auto local = py::dict(); 47 | local["x"] = py::int_(42); 48 | auto x = py::eval("x", global, local); 49 | return x.cast() == 42; 50 | }); 51 | 52 | m.def("test_eval_single_statement", []() { 53 | auto local = py::dict(); 54 | local["call_test"] = py::cpp_function([&]() -> int { 55 | return 42; 56 | }); 57 | 58 | auto result = py::eval("x = call_test()", py::dict(), local); 59 | auto x = local["x"].cast(); 60 | return result.is_none() && x == 42; 61 | }); 62 | 63 | m.def("test_eval_file", [global](py::str filename) { 64 | auto local = py::dict(); 65 | local["y"] = py::int_(43); 66 | 67 | int val_out; 68 | local["call_test2"] = py::cpp_function([&](int value) { val_out = value; }); 69 | 70 | auto result = py::eval_file(filename, global, local); 71 | return val_out == 43 && result.is_none(); 72 | }); 73 | 74 | m.def("test_eval_failure", []() { 75 | try { 76 | py::eval("nonsense code ..."); 77 | } catch (py::error_already_set &) { 78 | return true; 79 | } 80 | return false; 81 | }); 82 | 83 | m.def("test_eval_file_failure", []() { 84 | try { 85 | py::eval_file("non-existing file"); 86 | } catch (std::exception &) { 87 | return true; 88 | } 89 | return false; 90 | }); 91 | } 92 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_eval.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pybind11_tests import eval_ as m 3 | 4 | 5 | def test_evals(capture): 6 | with capture: 7 | assert m.test_eval_statements() 8 | assert capture == "Hello World!" 9 | 10 | assert m.test_eval() 11 | assert m.test_eval_single_statement() 12 | 13 | filename = os.path.join(os.path.dirname(__file__), "test_eval_call.py") 14 | assert m.test_eval_file(filename) 15 | 16 | assert m.test_eval_failure() 17 | assert m.test_eval_file_failure() 18 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_eval_call.py: -------------------------------------------------------------------------------- 1 | # This file is called from 'test_eval.py' 2 | 3 | if 'call_test2' in locals(): 4 | call_test2(y) # noqa: F821 undefined name 5 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_gil_scoped.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_gil_scoped.cpp -- acquire and release gil 3 | 4 | Copyright (c) 2017 Borja Zarco (Google LLC) 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include 12 | 13 | 14 | class VirtClass { 15 | public: 16 | virtual ~VirtClass() {} 17 | virtual void virtual_func() {} 18 | virtual void pure_virtual_func() = 0; 19 | }; 20 | 21 | class PyVirtClass : public VirtClass { 22 | void virtual_func() override { 23 | PYBIND11_OVERLOAD(void, VirtClass, virtual_func,); 24 | } 25 | void pure_virtual_func() override { 26 | PYBIND11_OVERLOAD_PURE(void, VirtClass, pure_virtual_func,); 27 | } 28 | }; 29 | 30 | TEST_SUBMODULE(gil_scoped, m) { 31 | py::class_(m, "VirtClass") 32 | .def(py::init<>()) 33 | .def("virtual_func", &VirtClass::virtual_func) 34 | .def("pure_virtual_func", &VirtClass::pure_virtual_func); 35 | 36 | m.def("test_callback_py_obj", 37 | [](py::object func) { func(); }); 38 | m.def("test_callback_std_func", 39 | [](const std::function &func) { func(); }); 40 | m.def("test_callback_virtual_func", 41 | [](VirtClass &virt) { virt.virtual_func(); }); 42 | m.def("test_callback_pure_virtual_func", 43 | [](VirtClass &virt) { virt.pure_virtual_func(); }); 44 | m.def("test_cross_module_gil", 45 | []() { 46 | auto cm = py::module::import("cross_module_gil_utils"); 47 | auto gil_acquire = reinterpret_cast( 48 | PyLong_AsVoidPtr(cm.attr("gil_acquire_funcaddr").ptr())); 49 | py::gil_scoped_release gil_release; 50 | gil_acquire(); 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_gil_scoped.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | import threading 3 | from pybind11_tests import gil_scoped as m 4 | 5 | 6 | def _run_in_process(target, *args, **kwargs): 7 | """Runs target in process and returns its exitcode after 10s (None if still alive).""" 8 | process = multiprocessing.Process(target=target, args=args, kwargs=kwargs) 9 | process.daemon = True 10 | try: 11 | process.start() 12 | # Do not need to wait much, 10s should be more than enough. 13 | process.join(timeout=10) 14 | return process.exitcode 15 | finally: 16 | if process.is_alive(): 17 | process.terminate() 18 | 19 | 20 | def _python_to_cpp_to_python(): 21 | """Calls different C++ functions that come back to Python.""" 22 | class ExtendedVirtClass(m.VirtClass): 23 | def virtual_func(self): 24 | pass 25 | 26 | def pure_virtual_func(self): 27 | pass 28 | 29 | extended = ExtendedVirtClass() 30 | m.test_callback_py_obj(lambda: None) 31 | m.test_callback_std_func(lambda: None) 32 | m.test_callback_virtual_func(extended) 33 | m.test_callback_pure_virtual_func(extended) 34 | 35 | 36 | def _python_to_cpp_to_python_from_threads(num_threads, parallel=False): 37 | """Calls different C++ functions that come back to Python, from Python threads.""" 38 | threads = [] 39 | for _ in range(num_threads): 40 | thread = threading.Thread(target=_python_to_cpp_to_python) 41 | thread.daemon = True 42 | thread.start() 43 | if parallel: 44 | threads.append(thread) 45 | else: 46 | thread.join() 47 | for thread in threads: 48 | thread.join() 49 | 50 | 51 | def test_python_to_cpp_to_python_from_thread(): 52 | """Makes sure there is no GIL deadlock when running in a thread. 53 | 54 | It runs in a separate process to be able to stop and assert if it deadlocks. 55 | """ 56 | assert _run_in_process(_python_to_cpp_to_python_from_threads, 1) == 0 57 | 58 | 59 | def test_python_to_cpp_to_python_from_thread_multiple_parallel(): 60 | """Makes sure there is no GIL deadlock when running in a thread multiple times in parallel. 61 | 62 | It runs in a separate process to be able to stop and assert if it deadlocks. 63 | """ 64 | assert _run_in_process(_python_to_cpp_to_python_from_threads, 8, parallel=True) == 0 65 | 66 | 67 | def test_python_to_cpp_to_python_from_thread_multiple_sequential(): 68 | """Makes sure there is no GIL deadlock when running in a thread multiple times sequentially. 69 | 70 | It runs in a separate process to be able to stop and assert if it deadlocks. 71 | """ 72 | assert _run_in_process(_python_to_cpp_to_python_from_threads, 8, parallel=False) == 0 73 | 74 | 75 | def test_python_to_cpp_to_python_from_process(): 76 | """Makes sure there is no GIL deadlock when using processes. 77 | 78 | This test is for completion, but it was never an issue. 79 | """ 80 | assert _run_in_process(_python_to_cpp_to_python) == 0 81 | 82 | 83 | def test_cross_module_gil(): 84 | """Makes sure that the GIL can be acquired by another module from a GIL-released state.""" 85 | m.test_cross_module_gil() # Should not raise a SIGSEGV 86 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_iostream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_iostream.cpp -- Usage of scoped_output_redirect 3 | 4 | Copyright (c) 2017 Henry F. Schreiner 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | 11 | #include 12 | #include "pybind11_tests.h" 13 | #include 14 | 15 | 16 | void noisy_function(std::string msg, bool flush) { 17 | 18 | std::cout << msg; 19 | if (flush) 20 | std::cout << std::flush; 21 | } 22 | 23 | void noisy_funct_dual(std::string msg, std::string emsg) { 24 | std::cout << msg; 25 | std::cerr << emsg; 26 | } 27 | 28 | TEST_SUBMODULE(iostream, m) { 29 | 30 | add_ostream_redirect(m); 31 | 32 | // test_evals 33 | 34 | m.def("captured_output_default", [](std::string msg) { 35 | py::scoped_ostream_redirect redir; 36 | std::cout << msg << std::flush; 37 | }); 38 | 39 | m.def("captured_output", [](std::string msg) { 40 | py::scoped_ostream_redirect redir(std::cout, py::module::import("sys").attr("stdout")); 41 | std::cout << msg << std::flush; 42 | }); 43 | 44 | m.def("guard_output", &noisy_function, 45 | py::call_guard(), 46 | py::arg("msg"), py::arg("flush")=true); 47 | 48 | m.def("captured_err", [](std::string msg) { 49 | py::scoped_ostream_redirect redir(std::cerr, py::module::import("sys").attr("stderr")); 50 | std::cerr << msg << std::flush; 51 | }); 52 | 53 | m.def("noisy_function", &noisy_function, py::arg("msg"), py::arg("flush") = true); 54 | 55 | m.def("dual_guard", &noisy_funct_dual, 56 | py::call_guard(), 57 | py::arg("msg"), py::arg("emsg")); 58 | 59 | m.def("raw_output", [](std::string msg) { 60 | std::cout << msg << std::flush; 61 | }); 62 | 63 | m.def("raw_err", [](std::string msg) { 64 | std::cerr << msg << std::flush; 65 | }); 66 | 67 | m.def("captured_dual", [](std::string msg, std::string emsg) { 68 | py::scoped_ostream_redirect redirout(std::cout, py::module::import("sys").attr("stdout")); 69 | py::scoped_ostream_redirect redirerr(std::cerr, py::module::import("sys").attr("stderr")); 70 | std::cout << msg << std::flush; 71 | std::cerr << emsg << std::flush; 72 | }); 73 | } 74 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_kwargs_and_defaults.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_kwargs_and_defaults.cpp -- keyword arguments and default values 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include "constructor_stats.h" 12 | #include 13 | 14 | TEST_SUBMODULE(kwargs_and_defaults, m) { 15 | auto kw_func = [](int x, int y) { return "x=" + std::to_string(x) + ", y=" + std::to_string(y); }; 16 | 17 | // test_named_arguments 18 | m.def("kw_func0", kw_func); 19 | m.def("kw_func1", kw_func, py::arg("x"), py::arg("y")); 20 | m.def("kw_func2", kw_func, py::arg("x") = 100, py::arg("y") = 200); 21 | m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!")); 22 | 23 | /* A fancier default argument */ 24 | std::vector list{{13, 17}}; 25 | m.def("kw_func4", [](const std::vector &entries) { 26 | std::string ret = "{"; 27 | for (int i : entries) 28 | ret += std::to_string(i) + " "; 29 | ret.back() = '}'; 30 | return ret; 31 | }, py::arg("myList") = list); 32 | 33 | m.def("kw_func_udl", kw_func, "x"_a, "y"_a=300); 34 | m.def("kw_func_udl_z", kw_func, "x"_a, "y"_a=0); 35 | 36 | // test_args_and_kwargs 37 | m.def("args_function", [](py::args args) -> py::tuple { 38 | return std::move(args); 39 | }); 40 | m.def("args_kwargs_function", [](py::args args, py::kwargs kwargs) { 41 | return py::make_tuple(args, kwargs); 42 | }); 43 | 44 | // test_mixed_args_and_kwargs 45 | m.def("mixed_plus_args", [](int i, double j, py::args args) { 46 | return py::make_tuple(i, j, args); 47 | }); 48 | m.def("mixed_plus_kwargs", [](int i, double j, py::kwargs kwargs) { 49 | return py::make_tuple(i, j, kwargs); 50 | }); 51 | auto mixed_plus_both = [](int i, double j, py::args args, py::kwargs kwargs) { 52 | return py::make_tuple(i, j, args, kwargs); 53 | }; 54 | m.def("mixed_plus_args_kwargs", mixed_plus_both); 55 | 56 | m.def("mixed_plus_args_kwargs_defaults", mixed_plus_both, 57 | py::arg("i") = 1, py::arg("j") = 3.14159); 58 | 59 | // test_args_refcount 60 | // PyPy needs a garbage collection to get the reference count values to match CPython's behaviour 61 | #ifdef PYPY_VERSION 62 | #define GC_IF_NEEDED ConstructorStats::gc() 63 | #else 64 | #define GC_IF_NEEDED 65 | #endif 66 | m.def("arg_refcount_h", [](py::handle h) { GC_IF_NEEDED; return h.ref_count(); }); 67 | m.def("arg_refcount_h", [](py::handle h, py::handle, py::handle) { GC_IF_NEEDED; return h.ref_count(); }); 68 | m.def("arg_refcount_o", [](py::object o) { GC_IF_NEEDED; return o.ref_count(); }); 69 | m.def("args_refcount", [](py::args a) { 70 | GC_IF_NEEDED; 71 | py::tuple t(a.size()); 72 | for (size_t i = 0; i < a.size(); i++) 73 | // Use raw Python API here to avoid an extra, intermediate incref on the tuple item: 74 | t[i] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast(i))); 75 | return t; 76 | }); 77 | m.def("mixed_args_refcount", [](py::object o, py::args a) { 78 | GC_IF_NEEDED; 79 | py::tuple t(a.size() + 1); 80 | t[0] = o.ref_count(); 81 | for (size_t i = 0; i < a.size(); i++) 82 | // Use raw Python API here to avoid an extra, intermediate incref on the tuple item: 83 | t[i + 1] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast(i))); 84 | return t; 85 | }); 86 | 87 | // pybind11 won't allow these to be bound: args and kwargs, if present, must be at the end. 88 | // Uncomment these to test that the static_assert is indeed working: 89 | // m.def("bad_args1", [](py::args, int) {}); 90 | // m.def("bad_args2", [](py::kwargs, int) {}); 91 | // m.def("bad_args3", [](py::kwargs, py::args) {}); 92 | // m.def("bad_args4", [](py::args, int, py::kwargs) {}); 93 | // m.def("bad_args5", [](py::args, py::kwargs, int) {}); 94 | // m.def("bad_args6", [](py::args, py::args) {}); 95 | // m.def("bad_args7", [](py::kwargs, py::kwargs) {}); 96 | 97 | // test_function_signatures (along with most of the above) 98 | struct KWClass { void foo(int, float) {} }; 99 | py::class_(m, "KWClass") 100 | .def("foo0", &KWClass::foo) 101 | .def("foo1", &KWClass::foo, "x"_a, "y"_a); 102 | } 103 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_local_bindings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_local_bindings.cpp -- tests the py::module_local class feature which makes a class 3 | binding local to the module in which it is defined. 4 | 5 | Copyright (c) 2017 Jason Rhinelander 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include "local_bindings.h" 13 | #include 14 | #include 15 | #include 16 | 17 | TEST_SUBMODULE(local_bindings, m) { 18 | // test_load_external 19 | m.def("load_external1", [](ExternalType1 &e) { return e.i; }); 20 | m.def("load_external2", [](ExternalType2 &e) { return e.i; }); 21 | 22 | // test_local_bindings 23 | // Register a class with py::module_local: 24 | bind_local(m, "LocalType", py::module_local()) 25 | .def("get3", [](LocalType &t) { return t.i + 3; }) 26 | ; 27 | 28 | m.def("local_value", [](LocalType &l) { return l.i; }); 29 | 30 | // test_nonlocal_failure 31 | // The main pybind11 test module is loaded first, so this registration will succeed (the second 32 | // one, in pybind11_cross_module_tests.cpp, is designed to fail): 33 | bind_local(m, "NonLocalType") 34 | .def(py::init()) 35 | .def("get", [](LocalType &i) { return i.i; }) 36 | ; 37 | 38 | // test_duplicate_local 39 | // py::module_local declarations should be visible across compilation units that get linked together; 40 | // this tries to register a duplicate local. It depends on a definition in test_class.cpp and 41 | // should raise a runtime error from the duplicate definition attempt. If test_class isn't 42 | // available it *also* throws a runtime error (with "test_class not enabled" as value). 43 | m.def("register_local_external", [m]() { 44 | auto main = py::module::import("pybind11_tests"); 45 | if (py::hasattr(main, "class_")) { 46 | bind_local(m, "LocalExternal", py::module_local()); 47 | } 48 | else throw std::runtime_error("test_class not enabled"); 49 | }); 50 | 51 | // test_stl_bind_local 52 | // stl_bind.h binders defaults to py::module_local if the types are local or converting: 53 | py::bind_vector(m, "LocalVec"); 54 | py::bind_map(m, "LocalMap"); 55 | // and global if the type (or one of the types, for the map) is global: 56 | py::bind_vector(m, "NonLocalVec"); 57 | py::bind_map(m, "NonLocalMap"); 58 | 59 | // test_stl_bind_global 60 | // They can, however, be overridden to global using `py::module_local(false)`: 61 | bind_local(m, "NonLocal2"); 62 | py::bind_vector(m, "LocalVec2", py::module_local()); 63 | py::bind_map(m, "NonLocalMap2", py::module_local(false)); 64 | 65 | // test_mixed_local_global 66 | // We try this both with the global type registered first and vice versa (the order shouldn't 67 | // matter). 68 | m.def("register_mixed_global", [m]() { 69 | bind_local(m, "MixedGlobalLocal", py::module_local(false)); 70 | }); 71 | m.def("register_mixed_local", [m]() { 72 | bind_local(m, "MixedLocalGlobal", py::module_local()); 73 | }); 74 | m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); 75 | m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); 76 | 77 | // test_internal_locals_differ 78 | m.def("local_cpp_types_addr", []() { return (uintptr_t) &py::detail::registered_local_types_cpp(); }); 79 | 80 | // test_stl_caster_vs_stl_bind 81 | m.def("load_vector_via_caster", [](std::vector v) { 82 | return std::accumulate(v.begin(), v.end(), 0); 83 | }); 84 | 85 | // test_cross_module_calls 86 | m.def("return_self", [](LocalVec *v) { return v; }); 87 | m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); 88 | 89 | class Cat : public pets::Pet { public: Cat(std::string name) : Pet(name) {}; }; 90 | py::class_(m, "Pet", py::module_local()) 91 | .def("get_name", &pets::Pet::name); 92 | // Binding for local extending class: 93 | py::class_(m, "Cat") 94 | .def(py::init()); 95 | m.def("pet_name", [](pets::Pet &p) { return p.name(); }); 96 | 97 | py::class_(m, "MixGL").def(py::init()); 98 | m.def("get_gl_value", [](MixGL &o) { return o.i + 10; }); 99 | 100 | py::class_(m, "MixGL2").def(py::init()); 101 | } 102 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_modules.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_modules.cpp -- nested modules, importing modules, and 3 | internal references 4 | 5 | Copyright (c) 2016 Wenzel Jakob 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include "constructor_stats.h" 13 | 14 | TEST_SUBMODULE(modules, m) { 15 | // test_nested_modules 16 | py::module m_sub = m.def_submodule("subsubmodule"); 17 | m_sub.def("submodule_func", []() { return "submodule_func()"; }); 18 | 19 | // test_reference_internal 20 | class A { 21 | public: 22 | A(int v) : v(v) { print_created(this, v); } 23 | ~A() { print_destroyed(this); } 24 | A(const A&) { print_copy_created(this); } 25 | A& operator=(const A ©) { print_copy_assigned(this); v = copy.v; return *this; } 26 | std::string toString() { return "A[" + std::to_string(v) + "]"; } 27 | private: 28 | int v; 29 | }; 30 | py::class_(m_sub, "A") 31 | .def(py::init()) 32 | .def("__repr__", &A::toString); 33 | 34 | class B { 35 | public: 36 | B() { print_default_created(this); } 37 | ~B() { print_destroyed(this); } 38 | B(const B&) { print_copy_created(this); } 39 | B& operator=(const B ©) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; } 40 | A &get_a1() { return a1; } 41 | A &get_a2() { return a2; } 42 | 43 | A a1{1}; 44 | A a2{2}; 45 | }; 46 | py::class_(m_sub, "B") 47 | .def(py::init<>()) 48 | .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal) 49 | .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal) 50 | .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default 51 | .def_readwrite("a2", &B::a2); 52 | 53 | m.attr("OD") = py::module::import("collections").attr("OrderedDict"); 54 | 55 | // test_duplicate_registration 56 | // Registering two things with the same name 57 | m.def("duplicate_registration", []() { 58 | class Dupe1 { }; 59 | class Dupe2 { }; 60 | class Dupe3 { }; 61 | class DupeException { }; 62 | 63 | auto dm = py::module("dummy"); 64 | auto failures = py::list(); 65 | 66 | py::class_(dm, "Dupe1"); 67 | py::class_(dm, "Dupe2"); 68 | dm.def("dupe1_factory", []() { return Dupe1(); }); 69 | py::exception(dm, "DupeException"); 70 | 71 | try { 72 | py::class_(dm, "Dupe1"); 73 | failures.append("Dupe1 class"); 74 | } catch (std::runtime_error &) {} 75 | try { 76 | dm.def("Dupe1", []() { return Dupe1(); }); 77 | failures.append("Dupe1 function"); 78 | } catch (std::runtime_error &) {} 79 | try { 80 | py::class_(dm, "dupe1_factory"); 81 | failures.append("dupe1_factory"); 82 | } catch (std::runtime_error &) {} 83 | try { 84 | py::exception(dm, "Dupe2"); 85 | failures.append("Dupe2"); 86 | } catch (std::runtime_error &) {} 87 | try { 88 | dm.def("DupeException", []() { return 30; }); 89 | failures.append("DupeException1"); 90 | } catch (std::runtime_error &) {} 91 | try { 92 | py::class_(dm, "DupeException"); 93 | failures.append("DupeException2"); 94 | } catch (std::runtime_error &) {} 95 | 96 | return failures; 97 | }); 98 | } 99 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_modules.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import modules as m 2 | from pybind11_tests.modules import subsubmodule as ms 3 | from pybind11_tests import ConstructorStats 4 | 5 | 6 | def test_nested_modules(): 7 | import pybind11_tests 8 | assert pybind11_tests.__name__ == "pybind11_tests" 9 | assert pybind11_tests.modules.__name__ == "pybind11_tests.modules" 10 | assert pybind11_tests.modules.subsubmodule.__name__ == "pybind11_tests.modules.subsubmodule" 11 | assert m.__name__ == "pybind11_tests.modules" 12 | assert ms.__name__ == "pybind11_tests.modules.subsubmodule" 13 | 14 | assert ms.submodule_func() == "submodule_func()" 15 | 16 | 17 | def test_reference_internal(): 18 | b = ms.B() 19 | assert str(b.get_a1()) == "A[1]" 20 | assert str(b.a1) == "A[1]" 21 | assert str(b.get_a2()) == "A[2]" 22 | assert str(b.a2) == "A[2]" 23 | 24 | b.a1 = ms.A(42) 25 | b.a2 = ms.A(43) 26 | assert str(b.get_a1()) == "A[42]" 27 | assert str(b.a1) == "A[42]" 28 | assert str(b.get_a2()) == "A[43]" 29 | assert str(b.a2) == "A[43]" 30 | 31 | astats, bstats = ConstructorStats.get(ms.A), ConstructorStats.get(ms.B) 32 | assert astats.alive() == 2 33 | assert bstats.alive() == 1 34 | del b 35 | assert astats.alive() == 0 36 | assert bstats.alive() == 0 37 | assert astats.values() == ['1', '2', '42', '43'] 38 | assert bstats.values() == [] 39 | assert astats.default_constructions == 0 40 | assert bstats.default_constructions == 1 41 | assert astats.copy_constructions == 0 42 | assert bstats.copy_constructions == 0 43 | # assert astats.move_constructions >= 0 # Don't invoke any 44 | # assert bstats.move_constructions >= 0 # Don't invoke any 45 | assert astats.copy_assignments == 2 46 | assert bstats.copy_assignments == 0 47 | assert astats.move_assignments == 0 48 | assert bstats.move_assignments == 0 49 | 50 | 51 | def test_importing(): 52 | from pybind11_tests.modules import OD 53 | from collections import OrderedDict 54 | 55 | assert OD is OrderedDict 56 | assert str(OD([(1, 'a'), (2, 'b')])) == "OrderedDict([(1, 'a'), (2, 'b')])" 57 | 58 | 59 | def test_pydoc(): 60 | """Pydoc needs to be able to provide help() for everything inside a pybind11 module""" 61 | import pybind11_tests 62 | import pydoc 63 | 64 | assert pybind11_tests.__name__ == "pybind11_tests" 65 | assert pybind11_tests.__doc__ == "pybind11 test module" 66 | assert pydoc.text.docmodule(pybind11_tests) 67 | 68 | 69 | def test_duplicate_registration(): 70 | """Registering two things with the same name""" 71 | 72 | assert m.duplicate_registration() == [] 73 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_numpy_vectorize.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_numpy_vectorize.cpp -- auto-vectorize functions over NumPy array 3 | arguments 4 | 5 | Copyright (c) 2016 Wenzel Jakob 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include 13 | 14 | double my_func(int x, float y, double z) { 15 | py::print("my_func(x:int={}, y:float={:.0f}, z:float={:.0f})"_s.format(x, y, z)); 16 | return (float) x*y*z; 17 | } 18 | 19 | TEST_SUBMODULE(numpy_vectorize, m) { 20 | try { py::module::import("numpy"); } 21 | catch (...) { return; } 22 | 23 | // test_vectorize, test_docs, test_array_collapse 24 | // Vectorize all arguments of a function (though non-vector arguments are also allowed) 25 | m.def("vectorized_func", py::vectorize(my_func)); 26 | 27 | // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization) 28 | m.def("vectorized_func2", 29 | [](py::array_t x, py::array_t y, float z) { 30 | return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y); 31 | } 32 | ); 33 | 34 | // Vectorize a complex-valued function 35 | m.def("vectorized_func3", py::vectorize( 36 | [](std::complex c) { return c * std::complex(2.f); } 37 | )); 38 | 39 | // test_type_selection 40 | // Numpy function which only accepts specific data types 41 | m.def("selective_func", [](py::array_t) { return "Int branch taken."; }); 42 | m.def("selective_func", [](py::array_t) { return "Float branch taken."; }); 43 | m.def("selective_func", [](py::array_t, py::array::c_style>) { return "Complex float branch taken."; }); 44 | 45 | 46 | // test_passthrough_arguments 47 | // Passthrough test: references and non-pod types should be automatically passed through (in the 48 | // function definition below, only `b`, `d`, and `g` are vectorized): 49 | struct NonPODClass { 50 | NonPODClass(int v) : value{v} {} 51 | int value; 52 | }; 53 | py::class_(m, "NonPODClass").def(py::init()); 54 | m.def("vec_passthrough", py::vectorize( 55 | [](double *a, double b, py::array_t c, const int &d, int &e, NonPODClass f, const double g) { 56 | return *a + b + c.at(0) + d + e + f.value + g; 57 | } 58 | )); 59 | 60 | // test_method_vectorization 61 | struct VectorizeTestClass { 62 | VectorizeTestClass(int v) : value{v} {}; 63 | float method(int x, float y) { return y + (float) (x + value); } 64 | int value = 0; 65 | }; 66 | py::class_ vtc(m, "VectorizeTestClass"); 67 | vtc .def(py::init()) 68 | .def_readwrite("value", &VectorizeTestClass::value); 69 | 70 | // Automatic vectorizing of methods 71 | vtc.def("method", py::vectorize(&VectorizeTestClass::method)); 72 | 73 | // test_trivial_broadcasting 74 | // Internal optimization test for whether the input is trivially broadcastable: 75 | py::enum_(m, "trivial") 76 | .value("f_trivial", py::detail::broadcast_trivial::f_trivial) 77 | .value("c_trivial", py::detail::broadcast_trivial::c_trivial) 78 | .value("non_trivial", py::detail::broadcast_trivial::non_trivial); 79 | m.def("vectorized_is_trivial", []( 80 | py::array_t arg1, 81 | py::array_t arg2, 82 | py::array_t arg3 83 | ) { 84 | ssize_t ndim; 85 | std::vector shape; 86 | std::array buffers {{ arg1.request(), arg2.request(), arg3.request() }}; 87 | return py::detail::broadcast(buffers, ndim, shape); 88 | }); 89 | } 90 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_opaque_types.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_opaque_types.cpp -- opaque types, passing void pointers 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include 12 | #include 13 | 14 | // IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures 15 | // 16 | // This also deliberately doesn't use the below StringList type alias to test 17 | // that MAKE_OPAQUE can handle a type containing a `,`. (The `std::allocator` 18 | // bit is just the default `std::vector` allocator). 19 | PYBIND11_MAKE_OPAQUE(std::vector>); 20 | 21 | using StringList = std::vector>; 22 | 23 | TEST_SUBMODULE(opaque_types, m) { 24 | // test_string_list 25 | py::class_(m, "StringList") 26 | .def(py::init<>()) 27 | .def("pop_back", &StringList::pop_back) 28 | /* There are multiple versions of push_back(), etc. Select the right ones. */ 29 | .def("push_back", (void (StringList::*)(const std::string &)) &StringList::push_back) 30 | .def("back", (std::string &(StringList::*)()) &StringList::back) 31 | .def("__len__", [](const StringList &v) { return v.size(); }) 32 | .def("__iter__", [](StringList &v) { 33 | return py::make_iterator(v.begin(), v.end()); 34 | }, py::keep_alive<0, 1>()); 35 | 36 | class ClassWithSTLVecProperty { 37 | public: 38 | StringList stringList; 39 | }; 40 | py::class_(m, "ClassWithSTLVecProperty") 41 | .def(py::init<>()) 42 | .def_readwrite("stringList", &ClassWithSTLVecProperty::stringList); 43 | 44 | m.def("print_opaque_list", [](const StringList &l) { 45 | std::string ret = "Opaque list: ["; 46 | bool first = true; 47 | for (auto entry : l) { 48 | if (!first) 49 | ret += ", "; 50 | ret += entry; 51 | first = false; 52 | } 53 | return ret + "]"; 54 | }); 55 | 56 | // test_pointers 57 | m.def("return_void_ptr", []() { return (void *) 0x1234; }); 58 | m.def("get_void_ptr_value", [](void *ptr) { return reinterpret_cast(ptr); }); 59 | m.def("return_null_str", []() { return (char *) nullptr; }); 60 | m.def("get_null_str_value", [](char *ptr) { return reinterpret_cast(ptr); }); 61 | 62 | m.def("return_unique_ptr", []() -> std::unique_ptr { 63 | StringList *result = new StringList(); 64 | result->push_back("some value"); 65 | return std::unique_ptr(result); 66 | }); 67 | } 68 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_opaque_types.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import opaque_types as m 3 | from pybind11_tests import ConstructorStats, UserType 4 | 5 | 6 | def test_string_list(): 7 | lst = m.StringList() 8 | lst.push_back("Element 1") 9 | lst.push_back("Element 2") 10 | assert m.print_opaque_list(lst) == "Opaque list: [Element 1, Element 2]" 11 | assert lst.back() == "Element 2" 12 | 13 | for i, k in enumerate(lst, start=1): 14 | assert k == "Element {}".format(i) 15 | lst.pop_back() 16 | assert m.print_opaque_list(lst) == "Opaque list: [Element 1]" 17 | 18 | cvp = m.ClassWithSTLVecProperty() 19 | assert m.print_opaque_list(cvp.stringList) == "Opaque list: []" 20 | 21 | cvp.stringList = lst 22 | cvp.stringList.push_back("Element 3") 23 | assert m.print_opaque_list(cvp.stringList) == "Opaque list: [Element 1, Element 3]" 24 | 25 | 26 | def test_pointers(msg): 27 | living_before = ConstructorStats.get(UserType).alive() 28 | assert m.get_void_ptr_value(m.return_void_ptr()) == 0x1234 29 | assert m.get_void_ptr_value(UserType()) # Should also work for other C++ types 30 | assert ConstructorStats.get(UserType).alive() == living_before 31 | 32 | with pytest.raises(TypeError) as excinfo: 33 | m.get_void_ptr_value([1, 2, 3]) # This should not work 34 | assert msg(excinfo.value) == """ 35 | get_void_ptr_value(): incompatible function arguments. The following argument types are supported: 36 | 1. (arg0: capsule) -> int 37 | 38 | Invoked with: [1, 2, 3] 39 | """ # noqa: E501 line too long 40 | 41 | assert m.return_null_str() is None 42 | assert m.get_null_str_value(m.return_null_str()) is not None 43 | 44 | ptr = m.return_unique_ptr() 45 | assert "StringList" in repr(ptr) 46 | assert m.print_opaque_list(ptr) == "Opaque list: [some value]" 47 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_operator_overloading.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import operators as m 3 | from pybind11_tests import ConstructorStats 4 | 5 | 6 | def test_operator_overloading(): 7 | v1 = m.Vector2(1, 2) 8 | v2 = m.Vector(3, -1) 9 | assert str(v1) == "[1.000000, 2.000000]" 10 | assert str(v2) == "[3.000000, -1.000000]" 11 | 12 | assert str(-v2) == "[-3.000000, 1.000000]" 13 | 14 | assert str(v1 + v2) == "[4.000000, 1.000000]" 15 | assert str(v1 - v2) == "[-2.000000, 3.000000]" 16 | assert str(v1 - 8) == "[-7.000000, -6.000000]" 17 | assert str(v1 + 8) == "[9.000000, 10.000000]" 18 | assert str(v1 * 8) == "[8.000000, 16.000000]" 19 | assert str(v1 / 8) == "[0.125000, 0.250000]" 20 | assert str(8 - v1) == "[7.000000, 6.000000]" 21 | assert str(8 + v1) == "[9.000000, 10.000000]" 22 | assert str(8 * v1) == "[8.000000, 16.000000]" 23 | assert str(8 / v1) == "[8.000000, 4.000000]" 24 | assert str(v1 * v2) == "[3.000000, -2.000000]" 25 | assert str(v2 / v1) == "[3.000000, -0.500000]" 26 | 27 | v1 += 2 * v2 28 | assert str(v1) == "[7.000000, 0.000000]" 29 | v1 -= v2 30 | assert str(v1) == "[4.000000, 1.000000]" 31 | v1 *= 2 32 | assert str(v1) == "[8.000000, 2.000000]" 33 | v1 /= 16 34 | assert str(v1) == "[0.500000, 0.125000]" 35 | v1 *= v2 36 | assert str(v1) == "[1.500000, -0.125000]" 37 | v2 /= v1 38 | assert str(v2) == "[2.000000, 8.000000]" 39 | 40 | assert hash(v1) == 4 41 | 42 | cstats = ConstructorStats.get(m.Vector2) 43 | assert cstats.alive() == 2 44 | del v1 45 | assert cstats.alive() == 1 46 | del v2 47 | assert cstats.alive() == 0 48 | assert cstats.values() == ['[1.000000, 2.000000]', '[3.000000, -1.000000]', 49 | '[-3.000000, 1.000000]', '[4.000000, 1.000000]', 50 | '[-2.000000, 3.000000]', '[-7.000000, -6.000000]', 51 | '[9.000000, 10.000000]', '[8.000000, 16.000000]', 52 | '[0.125000, 0.250000]', '[7.000000, 6.000000]', 53 | '[9.000000, 10.000000]', '[8.000000, 16.000000]', 54 | '[8.000000, 4.000000]', '[3.000000, -2.000000]', 55 | '[3.000000, -0.500000]', '[6.000000, -2.000000]'] 56 | assert cstats.default_constructions == 0 57 | assert cstats.copy_constructions == 0 58 | assert cstats.move_constructions >= 10 59 | assert cstats.copy_assignments == 0 60 | assert cstats.move_assignments == 0 61 | 62 | 63 | def test_operators_notimplemented(): 64 | """#393: need to return NotSupported to ensure correct arithmetic operator behavior""" 65 | 66 | c1, c2 = m.C1(), m.C2() 67 | assert c1 + c1 == 11 68 | assert c2 + c2 == 22 69 | assert c2 + c1 == 21 70 | assert c1 + c2 == 12 71 | 72 | 73 | def test_nested(): 74 | """#328: first member in a class can't be used in operators""" 75 | 76 | a = m.NestA() 77 | b = m.NestB() 78 | c = m.NestC() 79 | 80 | a += 10 81 | assert m.get_NestA(a) == 13 82 | b.a += 100 83 | assert m.get_NestA(b.a) == 103 84 | c.b.a += 1000 85 | assert m.get_NestA(c.b.a) == 1003 86 | b -= 1 87 | assert m.get_NestB(b) == 3 88 | c.b -= 3 89 | assert m.get_NestB(c.b) == 1 90 | c *= 7 91 | assert m.get_NestC(c) == 35 92 | 93 | abase = a.as_base() 94 | assert abase.value == -2 95 | a.as_base().value += 44 96 | assert abase.value == 42 97 | assert c.b.a.as_base().value == -2 98 | c.b.a.as_base().value += 44 99 | assert c.b.a.as_base().value == 42 100 | 101 | del c 102 | pytest.gc_collect() 103 | del a # Shouldn't delete while abase is still alive 104 | pytest.gc_collect() 105 | 106 | assert abase.value == 42 107 | del abase, b 108 | pytest.gc_collect() 109 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_pickling.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import pickling as m 3 | 4 | try: 5 | import cPickle as pickle # Use cPickle on Python 2.7 6 | except ImportError: 7 | import pickle 8 | 9 | 10 | @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"]) 11 | def test_roundtrip(cls_name): 12 | cls = getattr(m, cls_name) 13 | p = cls("test_value") 14 | p.setExtra1(15) 15 | p.setExtra2(48) 16 | 17 | data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 18 | p2 = pickle.loads(data) 19 | assert p2.value() == p.value() 20 | assert p2.extra1() == p.extra1() 21 | assert p2.extra2() == p.extra2() 22 | 23 | 24 | @pytest.unsupported_on_pypy 25 | @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"]) 26 | def test_roundtrip_with_dict(cls_name): 27 | cls = getattr(m, cls_name) 28 | p = cls("test_value") 29 | p.extra = 15 30 | p.dynamic = "Attribute" 31 | 32 | data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) 33 | p2 = pickle.loads(data) 34 | assert p2.value == p.value 35 | assert p2.extra == p.extra 36 | assert p2.dynamic == p.dynamic 37 | 38 | 39 | def test_enum_pickle(): 40 | from pybind11_tests import enums as e 41 | data = pickle.dumps(e.EOne, 2) 42 | assert e.EOne == pickle.loads(data) 43 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_stl_binders.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_stl_binders.cpp -- Usage of stl_binders functions 3 | 4 | Copyright (c) 2016 Sergey Lyskov 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | class El { 19 | public: 20 | El() = delete; 21 | El(int v) : a(v) { } 22 | 23 | int a; 24 | }; 25 | 26 | std::ostream & operator<<(std::ostream &s, El const&v) { 27 | s << "El{" << v.a << '}'; 28 | return s; 29 | } 30 | 31 | /// Issue #487: binding std::vector with E non-copyable 32 | class E_nc { 33 | public: 34 | explicit E_nc(int i) : value{i} {} 35 | E_nc(const E_nc &) = delete; 36 | E_nc &operator=(const E_nc &) = delete; 37 | E_nc(E_nc &&) = default; 38 | E_nc &operator=(E_nc &&) = default; 39 | 40 | int value; 41 | }; 42 | 43 | template Container *one_to_n(int n) { 44 | auto v = new Container(); 45 | for (int i = 1; i <= n; i++) 46 | v->emplace_back(i); 47 | return v; 48 | } 49 | 50 | template Map *times_ten(int n) { 51 | auto m = new Map(); 52 | for (int i = 1; i <= n; i++) 53 | m->emplace(int(i), E_nc(10*i)); 54 | return m; 55 | } 56 | 57 | TEST_SUBMODULE(stl_binders, m) { 58 | // test_vector_int 59 | py::bind_vector>(m, "VectorInt", py::buffer_protocol()); 60 | 61 | // test_vector_custom 62 | py::class_(m, "El") 63 | .def(py::init()); 64 | py::bind_vector>(m, "VectorEl"); 65 | py::bind_vector>>(m, "VectorVectorEl"); 66 | 67 | // test_map_string_double 68 | py::bind_map>(m, "MapStringDouble"); 69 | py::bind_map>(m, "UnorderedMapStringDouble"); 70 | 71 | // test_map_string_double_const 72 | py::bind_map>(m, "MapStringDoubleConst"); 73 | py::bind_map>(m, "UnorderedMapStringDoubleConst"); 74 | 75 | py::class_(m, "ENC") 76 | .def(py::init()) 77 | .def_readwrite("value", &E_nc::value); 78 | 79 | // test_noncopyable_containers 80 | py::bind_vector>(m, "VectorENC"); 81 | m.def("get_vnc", &one_to_n>, py::return_value_policy::reference); 82 | py::bind_vector>(m, "DequeENC"); 83 | m.def("get_dnc", &one_to_n>, py::return_value_policy::reference); 84 | py::bind_map>(m, "MapENC"); 85 | m.def("get_mnc", ×_ten>, py::return_value_policy::reference); 86 | py::bind_map>(m, "UmapENC"); 87 | m.def("get_umnc", ×_ten>, py::return_value_policy::reference); 88 | 89 | // test_vector_buffer 90 | py::bind_vector>(m, "VectorUChar", py::buffer_protocol()); 91 | // no dtype declared for this version: 92 | struct VUndeclStruct { bool w; uint32_t x; double y; bool z; }; 93 | m.def("create_undeclstruct", [m] () mutable { 94 | py::bind_vector>(m, "VectorUndeclStruct", py::buffer_protocol()); 95 | }); 96 | 97 | // The rest depends on numpy: 98 | try { py::module::import("numpy"); } 99 | catch (...) { return; } 100 | 101 | // test_vector_buffer_numpy 102 | struct VStruct { bool w; uint32_t x; double y; bool z; }; 103 | PYBIND11_NUMPY_DTYPE(VStruct, w, x, y, z); 104 | py::class_(m, "VStruct").def_readwrite("x", &VStruct::x); 105 | py::bind_vector>(m, "VectorStruct", py::buffer_protocol()); 106 | m.def("get_vectorstruct", [] {return std::vector {{0, 5, 3.0, 1}, {1, 30, -1e4, 0}};}); 107 | } 108 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_tagbased_polymorphic.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import tagbased_polymorphic as m 2 | 3 | 4 | def test_downcast(): 5 | zoo = m.create_zoo() 6 | assert [type(animal) for animal in zoo] == [ 7 | m.Labrador, m.Dog, m.Chihuahua, m.Cat, m.Panther 8 | ] 9 | assert [animal.name for animal in zoo] == [ 10 | "Fido", "Ginger", "Hertzl", "Tiger", "Leo" 11 | ] 12 | zoo[1].sound = "woooooo" 13 | assert [dog.bark() for dog in zoo[:3]] == [ 14 | "Labrador Fido goes WOOF!", 15 | "Dog Ginger goes woooooo", 16 | "Chihuahua Hertzl goes iyiyiyiyiyi and runs in circles" 17 | ] 18 | assert [cat.purr() for cat in zoo[3:]] == ["mrowr", "mrrrRRRRRR"] 19 | zoo[0].excitement -= 1000 20 | assert zoo[0].excitement == 14000 21 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_union.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_class.cpp -- test py::class_ definitions and basic functionality 3 | 4 | Copyright (c) 2019 Roland Dreier 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(union_, m) { 13 | union TestUnion { 14 | int value_int; 15 | unsigned value_uint; 16 | }; 17 | 18 | py::class_(m, "TestUnion") 19 | .def(py::init<>()) 20 | .def_readonly("as_int", &TestUnion::value_int) 21 | .def_readwrite("as_uint", &TestUnion::value_uint); 22 | } 23 | -------------------------------------------------------------------------------- /plugin/pybind11/tests/test_union.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import union_ as m 2 | 3 | 4 | def test_union(): 5 | instance = m.TestUnion() 6 | 7 | instance.as_uint = 10 8 | assert instance.as_int == 10 9 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/FindCatch.cmake: -------------------------------------------------------------------------------- 1 | # - Find the Catch test framework or download it (single header) 2 | # 3 | # This is a quick module for internal use. It assumes that Catch is 4 | # REQUIRED and that a minimum version is provided (not EXACT). If 5 | # a suitable version isn't found locally, the single header file 6 | # will be downloaded and placed in the build dir: PROJECT_BINARY_DIR. 7 | # 8 | # This code sets the following variables: 9 | # CATCH_INCLUDE_DIR - path to catch.hpp 10 | # CATCH_VERSION - version number 11 | 12 | if(NOT Catch_FIND_VERSION) 13 | message(FATAL_ERROR "A version number must be specified.") 14 | elseif(Catch_FIND_REQUIRED) 15 | message(FATAL_ERROR "This module assumes Catch is not required.") 16 | elseif(Catch_FIND_VERSION_EXACT) 17 | message(FATAL_ERROR "Exact version numbers are not supported, only minimum.") 18 | endif() 19 | 20 | # Extract the version number from catch.hpp 21 | function(_get_catch_version) 22 | file(STRINGS "${CATCH_INCLUDE_DIR}/catch.hpp" version_line REGEX "Catch v.*" LIMIT_COUNT 1) 23 | if(version_line MATCHES "Catch v([0-9]+)\\.([0-9]+)\\.([0-9]+)") 24 | set(CATCH_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}" PARENT_SCOPE) 25 | endif() 26 | endfunction() 27 | 28 | # Download the single-header version of Catch 29 | function(_download_catch version destination_dir) 30 | message(STATUS "Downloading catch v${version}...") 31 | set(url https://github.com/philsquared/Catch/releases/download/v${version}/catch.hpp) 32 | file(DOWNLOAD ${url} "${destination_dir}/catch.hpp" STATUS status) 33 | list(GET status 0 error) 34 | if(error) 35 | message(FATAL_ERROR "Could not download ${url}") 36 | endif() 37 | set(CATCH_INCLUDE_DIR "${destination_dir}" CACHE INTERNAL "") 38 | endfunction() 39 | 40 | # Look for catch locally 41 | find_path(CATCH_INCLUDE_DIR NAMES catch.hpp PATH_SUFFIXES catch) 42 | if(CATCH_INCLUDE_DIR) 43 | _get_catch_version() 44 | endif() 45 | 46 | # Download the header if it wasn't found or if it's outdated 47 | if(NOT CATCH_VERSION OR CATCH_VERSION VERSION_LESS ${Catch_FIND_VERSION}) 48 | if(DOWNLOAD_CATCH) 49 | _download_catch(${Catch_FIND_VERSION} "${PROJECT_BINARY_DIR}/catch/") 50 | _get_catch_version() 51 | else() 52 | set(CATCH_FOUND FALSE) 53 | return() 54 | endif() 55 | endif() 56 | 57 | set(CATCH_FOUND TRUE) 58 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/FindEigen3.cmake: -------------------------------------------------------------------------------- 1 | # - Try to find Eigen3 lib 2 | # 3 | # This module supports requiring a minimum version, e.g. you can do 4 | # find_package(Eigen3 3.1.2) 5 | # to require version 3.1.2 or newer of Eigen3. 6 | # 7 | # Once done this will define 8 | # 9 | # EIGEN3_FOUND - system has eigen lib with correct version 10 | # EIGEN3_INCLUDE_DIR - the eigen include directory 11 | # EIGEN3_VERSION - eigen version 12 | 13 | # Copyright (c) 2006, 2007 Montel Laurent, 14 | # Copyright (c) 2008, 2009 Gael Guennebaud, 15 | # Copyright (c) 2009 Benoit Jacob 16 | # Redistribution and use is allowed according to the terms of the 2-clause BSD license. 17 | 18 | if(NOT Eigen3_FIND_VERSION) 19 | if(NOT Eigen3_FIND_VERSION_MAJOR) 20 | set(Eigen3_FIND_VERSION_MAJOR 2) 21 | endif(NOT Eigen3_FIND_VERSION_MAJOR) 22 | if(NOT Eigen3_FIND_VERSION_MINOR) 23 | set(Eigen3_FIND_VERSION_MINOR 91) 24 | endif(NOT Eigen3_FIND_VERSION_MINOR) 25 | if(NOT Eigen3_FIND_VERSION_PATCH) 26 | set(Eigen3_FIND_VERSION_PATCH 0) 27 | endif(NOT Eigen3_FIND_VERSION_PATCH) 28 | 29 | set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}") 30 | endif(NOT Eigen3_FIND_VERSION) 31 | 32 | macro(_eigen3_check_version) 33 | file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header) 34 | 35 | string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}") 36 | set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}") 37 | string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}") 38 | set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}") 39 | string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}") 40 | set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}") 41 | 42 | set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION}) 43 | if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 44 | set(EIGEN3_VERSION_OK FALSE) 45 | else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 46 | set(EIGEN3_VERSION_OK TRUE) 47 | endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 48 | 49 | if(NOT EIGEN3_VERSION_OK) 50 | 51 | message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, " 52 | "but at least version ${Eigen3_FIND_VERSION} is required") 53 | endif(NOT EIGEN3_VERSION_OK) 54 | endmacro(_eigen3_check_version) 55 | 56 | if (EIGEN3_INCLUDE_DIR) 57 | 58 | # in cache already 59 | _eigen3_check_version() 60 | set(EIGEN3_FOUND ${EIGEN3_VERSION_OK}) 61 | 62 | else (EIGEN3_INCLUDE_DIR) 63 | 64 | find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library 65 | PATHS 66 | ${CMAKE_INSTALL_PREFIX}/include 67 | ${KDE4_INCLUDE_DIR} 68 | PATH_SUFFIXES eigen3 eigen 69 | ) 70 | 71 | if(EIGEN3_INCLUDE_DIR) 72 | _eigen3_check_version() 73 | endif(EIGEN3_INCLUDE_DIR) 74 | 75 | include(FindPackageHandleStandardArgs) 76 | find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) 77 | 78 | mark_as_advanced(EIGEN3_INCLUDE_DIR) 79 | 80 | endif(EIGEN3_INCLUDE_DIR) 81 | 82 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/check-style.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Script to check include/test code for common pybind11 code style errors. 4 | # 5 | # This script currently checks for 6 | # 7 | # 1. use of tabs instead of spaces 8 | # 2. MSDOS-style CRLF endings 9 | # 3. trailing spaces 10 | # 4. missing space between keyword and parenthesis, e.g.: for(, if(, while( 11 | # 5. Missing space between right parenthesis and brace, e.g. 'for (...){' 12 | # 6. opening brace on its own line. It should always be on the same line as the 13 | # if/while/for/do statement. 14 | # 15 | # Invoke as: tools/check-style.sh 16 | # 17 | 18 | check_style_errors=0 19 | IFS=$'\n' 20 | 21 | found="$( GREP_COLORS='mt=41' GREP_COLOR='41' grep $'\t' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )" 22 | if [ -n "$found" ]; then 23 | # The mt=41 sets a red background for matched tabs: 24 | echo -e '\033[31;01mError: found tab characters in the following files:\033[0m' 25 | check_style_errors=1 26 | echo "$found" | sed -e 's/^/ /' 27 | fi 28 | 29 | 30 | found="$( grep -IUlr $'\r' include tests/*.{cpp,py,h} docs/*.rst --color=always )" 31 | if [ -n "$found" ]; then 32 | echo -e '\033[31;01mError: found CRLF characters in the following files:\033[0m' 33 | check_style_errors=1 34 | echo "$found" | sed -e 's/^/ /' 35 | fi 36 | 37 | found="$(GREP_COLORS='mt=41' GREP_COLOR='41' grep '[[:blank:]]\+$' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )" 38 | if [ -n "$found" ]; then 39 | # The mt=41 sets a red background for matched trailing spaces 40 | echo -e '\033[31;01mError: found trailing spaces in the following files:\033[0m' 41 | check_style_errors=1 42 | echo "$found" | sed -e 's/^/ /' 43 | fi 44 | 45 | found="$(grep '\<\(if\|for\|while\|catch\)(\|){' include tests/*.{cpp,h} -rn --color=always)" 46 | if [ -n "$found" ]; then 47 | echo -e '\033[31;01mError: found the following coding style problems:\033[0m' 48 | check_style_errors=1 49 | echo "$found" | sed -e 's/^/ /' 50 | fi 51 | 52 | found="$(awk ' 53 | function prefix(filename, lineno) { 54 | return " \033[35m" filename "\033[36m:\033[32m" lineno "\033[36m:\033[0m" 55 | } 56 | function mark(pattern, string) { sub(pattern, "\033[01;31m&\033[0m", string); return string } 57 | last && /^\s*{/ { 58 | print prefix(FILENAME, FNR-1) mark("\\)\\s*$", last) 59 | print prefix(FILENAME, FNR) mark("^\\s*{", $0) 60 | last="" 61 | } 62 | { last = /(if|for|while|catch|switch)\s*\(.*\)\s*$/ ? $0 : "" } 63 | ' $(find include -type f) tests/*.{cpp,h} docs/*.rst)" 64 | if [ -n "$found" ]; then 65 | check_style_errors=1 66 | echo -e '\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\033[0m' 67 | echo "$found" 68 | fi 69 | 70 | exit $check_style_errors 71 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/clang/.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.swo 3 | *.pyc 4 | __pycache__ 5 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/clang/LICENSE.TXT: -------------------------------------------------------------------------------- 1 | ============================================================================== 2 | LLVM Release License 3 | ============================================================================== 4 | University of Illinois/NCSA 5 | Open Source License 6 | 7 | Copyright (c) 2007-2012 University of Illinois at Urbana-Champaign. 8 | All rights reserved. 9 | 10 | Developed by: 11 | 12 | LLVM Team 13 | 14 | University of Illinois at Urbana-Champaign 15 | 16 | http://llvm.org 17 | 18 | Permission is hereby granted, free of charge, to any person obtaining a copy of 19 | this software and associated documentation files (the "Software"), to deal with 20 | the Software without restriction, including without limitation the rights to 21 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 22 | of the Software, and to permit persons to whom the Software is furnished to do 23 | so, subject to the following conditions: 24 | 25 | * Redistributions of source code must retain the above copyright notice, 26 | this list of conditions and the following disclaimers. 27 | 28 | * Redistributions in binary form must reproduce the above copyright notice, 29 | this list of conditions and the following disclaimers in the 30 | documentation and/or other materials provided with the distribution. 31 | 32 | * Neither the names of the LLVM Team, University of Illinois at 33 | Urbana-Champaign, nor the names of its contributors may be used to 34 | endorse or promote products derived from this Software without specific 35 | prior written permission. 36 | 37 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 38 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 39 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 40 | CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 41 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 42 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE 43 | SOFTWARE. 44 | 45 | ============================================================================== 46 | The LLVM software contains code written by third parties. Such software will 47 | have its own individual LICENSE.TXT file in the directory in which it appears. 48 | This file will describe the copyrights, license, and restrictions which apply 49 | to that code. 50 | 51 | The disclaimer of warranty in the University of Illinois Open Source License 52 | applies to all code in the LLVM Distribution, and nothing in any of the 53 | other licenses gives permission to use the names of the LLVM Team or the 54 | University of Illinois to endorse or promote products derived from this 55 | Software. 56 | 57 | The following pieces of software have additional or alternate copyrights, 58 | licenses, and/or restrictions: 59 | 60 | Program Directory 61 | ------- --------- 62 | 63 | 64 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/clang/README.md: -------------------------------------------------------------------------------- 1 | This is simply clang's Python bindings (clang.cindex) ported to Python 3. Please see http://llvm.org/svn/llvm-project/cfe/trunk/bindings/python/ for the original project. 2 | 3 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/clang/__init__.py: -------------------------------------------------------------------------------- 1 | #===- __init__.py - Clang Python Bindings --------------------*- python -*--===# 2 | # 3 | # The LLVM Compiler Infrastructure 4 | # 5 | # This file is distributed under the University of Illinois Open Source 6 | # License. See LICENSE.TXT for details. 7 | # 8 | #===------------------------------------------------------------------------===# 9 | 10 | r""" 11 | Clang Library Bindings 12 | ====================== 13 | 14 | This package provides access to the Clang compiler and libraries. 15 | 16 | The available modules are: 17 | 18 | cindex 19 | 20 | Bindings for the Clang indexing library. 21 | """ 22 | 23 | __all__ = ['cindex'] 24 | 25 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/clang/enumerations.py: -------------------------------------------------------------------------------- 1 | #===- enumerations.py - Python Enumerations ------------------*- python -*--===# 2 | # 3 | # The LLVM Compiler Infrastructure 4 | # 5 | # This file is distributed under the University of Illinois Open Source 6 | # License. See LICENSE.TXT for details. 7 | # 8 | #===------------------------------------------------------------------------===# 9 | 10 | """ 11 | Clang Enumerations 12 | ================== 13 | 14 | This module provides static definitions of enumerations that exist in libclang. 15 | 16 | Enumerations are typically defined as a list of tuples. The exported values are 17 | typically munged into other types or classes at module load time. 18 | 19 | All enumerations are centrally defined in this file so they are all grouped 20 | together and easier to audit. And, maybe even one day this file will be 21 | automatically generated by scanning the libclang headers! 22 | """ 23 | 24 | # Maps to CXTokenKind. Note that libclang maintains a separate set of token 25 | # enumerations from the C++ API. 26 | TokenKinds = [ 27 | ('PUNCTUATION', 0), 28 | ('KEYWORD', 1), 29 | ('IDENTIFIER', 2), 30 | ('LITERAL', 3), 31 | ('COMMENT', 4), 32 | ] 33 | 34 | __all__ = ['TokenKinds'] 35 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/libsize.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division 2 | import os 3 | import sys 4 | 5 | # Internal build script for generating debugging test .so size. 6 | # Usage: 7 | # python libsize.py file.so save.txt -- displays the size of file.so and, if save.txt exists, compares it to the 8 | # size in it, then overwrites save.txt with the new size for future runs. 9 | 10 | if len(sys.argv) != 3: 11 | sys.exit("Invalid arguments: usage: python libsize.py file.so save.txt") 12 | 13 | lib = sys.argv[1] 14 | save = sys.argv[2] 15 | 16 | if not os.path.exists(lib): 17 | sys.exit("Error: requested file ({}) does not exist".format(lib)) 18 | 19 | libsize = os.path.getsize(lib) 20 | 21 | print("------", os.path.basename(lib), "file size:", libsize, end='') 22 | 23 | if os.path.exists(save): 24 | with open(save) as sf: 25 | oldsize = int(sf.readline()) 26 | 27 | if oldsize > 0: 28 | change = libsize - oldsize 29 | if change == 0: 30 | print(" (no change)") 31 | else: 32 | print(" (change of {:+} bytes = {:+.2%})".format(change, change / oldsize)) 33 | else: 34 | print() 35 | 36 | with open(save, 'w') as sf: 37 | sf.write(str(libsize)) 38 | 39 | -------------------------------------------------------------------------------- /plugin/pybind11/tools/pybind11Config.cmake.in: -------------------------------------------------------------------------------- 1 | # pybind11Config.cmake 2 | # -------------------- 3 | # 4 | # PYBIND11 cmake module. 5 | # This module sets the following variables in your project:: 6 | # 7 | # pybind11_FOUND - true if pybind11 and all required components found on the system 8 | # pybind11_VERSION - pybind11 version in format Major.Minor.Release 9 | # pybind11_INCLUDE_DIRS - Directories where pybind11 and python headers are located. 10 | # pybind11_INCLUDE_DIR - Directory where pybind11 headers are located. 11 | # pybind11_DEFINITIONS - Definitions necessary to use pybind11, namely USING_pybind11. 12 | # pybind11_LIBRARIES - compile flags and python libraries (as needed) to link against. 13 | # pybind11_LIBRARY - empty. 14 | # CMAKE_MODULE_PATH - appends location of accompanying FindPythonLibsNew.cmake and 15 | # pybind11Tools.cmake modules. 16 | # 17 | # 18 | # Available components: None 19 | # 20 | # 21 | # Exported targets:: 22 | # 23 | # If pybind11 is found, this module defines the following :prop_tgt:`IMPORTED` 24 | # interface library targets:: 25 | # 26 | # pybind11::module - for extension modules 27 | # pybind11::embed - for embedding the Python interpreter 28 | # 29 | # Python headers, libraries (as needed by platform), and the C++ standard 30 | # are attached to the target. Set PythonLibsNew variables to influence 31 | # python detection and PYBIND11_CPP_STANDARD (-std=c++11 or -std=c++14) to 32 | # influence standard setting. :: 33 | # 34 | # find_package(pybind11 CONFIG REQUIRED) 35 | # message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 36 | # 37 | # # Create an extension module 38 | # add_library(mylib MODULE main.cpp) 39 | # target_link_libraries(mylib pybind11::module) 40 | # 41 | # # Or embed the Python interpreter into an executable 42 | # add_executable(myexe main.cpp) 43 | # target_link_libraries(myexe pybind11::embed) 44 | # 45 | # Suggested usage:: 46 | # 47 | # find_package with version info is not recommended except for release versions. :: 48 | # 49 | # find_package(pybind11 CONFIG) 50 | # find_package(pybind11 2.0 EXACT CONFIG REQUIRED) 51 | # 52 | # 53 | # The following variables can be set to guide the search for this package:: 54 | # 55 | # pybind11_DIR - CMake variable, set to directory containing this Config file 56 | # CMAKE_PREFIX_PATH - CMake variable, set to root directory of this package 57 | # PATH - environment variable, set to bin directory of this package 58 | # CMAKE_DISABLE_FIND_PACKAGE_pybind11 - CMake variable, disables 59 | # find_package(pybind11) when not REQUIRED, perhaps to force internal build 60 | 61 | @PACKAGE_INIT@ 62 | 63 | set(PN pybind11) 64 | 65 | # location of pybind11/pybind11.h 66 | set(${PN}_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/@CMAKE_INSTALL_INCLUDEDIR@") 67 | 68 | set(${PN}_LIBRARY "") 69 | set(${PN}_DEFINITIONS USING_${PN}) 70 | 71 | check_required_components(${PN}) 72 | 73 | # make detectable the FindPythonLibsNew.cmake module 74 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) 75 | 76 | include(pybind11Tools) 77 | 78 | if(NOT (CMAKE_VERSION VERSION_LESS 3.0)) 79 | #----------------------------------------------------------------------------- 80 | # Don't include targets if this file is being picked up by another 81 | # project which has already built this as a subproject 82 | #----------------------------------------------------------------------------- 83 | if(NOT TARGET ${PN}::pybind11) 84 | include("${CMAKE_CURRENT_LIST_DIR}/${PN}Targets.cmake") 85 | 86 | find_package(PythonLibsNew ${PYBIND11_PYTHON_VERSION} MODULE REQUIRED) 87 | set_property(TARGET ${PN}::pybind11 APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PYTHON_INCLUDE_DIRS}) 88 | set_property(TARGET ${PN}::embed APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${PYTHON_LIBRARIES}) 89 | if(WIN32 OR CYGWIN) 90 | set_property(TARGET ${PN}::module APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${PYTHON_LIBRARIES}) 91 | endif() 92 | 93 | if(CMAKE_VERSION VERSION_LESS 3.3) 94 | set_property(TARGET ${PN}::pybind11 APPEND PROPERTY INTERFACE_COMPILE_OPTIONS "${PYBIND11_CPP_STANDARD}") 95 | else() 96 | set_property(TARGET ${PN}::pybind11 APPEND PROPERTY INTERFACE_COMPILE_OPTIONS $<$:${PYBIND11_CPP_STANDARD}>) 97 | endif() 98 | 99 | get_property(_iid TARGET ${PN}::pybind11 PROPERTY INTERFACE_INCLUDE_DIRECTORIES) 100 | get_property(_ill TARGET ${PN}::module PROPERTY INTERFACE_LINK_LIBRARIES) 101 | set(${PN}_INCLUDE_DIRS ${_iid}) 102 | set(${PN}_LIBRARIES ${_ico} ${_ill}) 103 | endif() 104 | endif() 105 | -------------------------------------------------------------------------------- /rand_image/test_img.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/rand_image/test_img.npy -------------------------------------------------------------------------------- /rand_image/test_img.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/rand_image/test_img.pt -------------------------------------------------------------------------------- /rand_image/test_label.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/rand_image/test_label.npy -------------------------------------------------------------------------------- /rand_image/test_label.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/rand_image/test_label.pt -------------------------------------------------------------------------------- /saved_models/addernet_mnist.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/saved_models/addernet_mnist.pth -------------------------------------------------------------------------------- /saved_models/addernet_mnist_v1.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/saved_models/addernet_mnist_v1.pth -------------------------------------------------------------------------------- /saved_models/addernet_mnist_v2.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinthysl/AdderNetTensorRT/b4164cf9c9fd818430b38344c054ddb49c3a967e/saved_models/addernet_mnist_v2.pth -------------------------------------------------------------------------------- /test/TestAdder2dPlugin.cpp: -------------------------------------------------------------------------------- 1 | #include "Adder2dPlugin.h" 2 | #include 3 | #include 4 | 5 | int main(int argc, char** argv) { 6 | 7 | int nbWeights, nbInputChannels, nInputHeight, nInputWidth, filterSize, nbFilters, stride, padding; 8 | nbInputChannels=4; nInputHeight=32; nInputWidth=32; 9 | filterSize=3; nbFilters=64; stride=1; padding=0; 10 | nbWeights = nbInputChannels*filterSize*filterSize*nbFilters; 11 | std::vector weightValues; 12 | for(int i=0; i (rand()) / static_cast (RAND_MAX); 14 | weightValues.push_back(r); 15 | } 16 | nvinfer1::Weights weights{nvinfer1::DataType::kFLOAT, weightValues.data(), (int64_t)weightValues.size()}; 17 | 18 | auto plugin_obj = new Adder2dPlugin(&weights, nbWeights, nbInputChannels, nInputHeight, nInputWidth, 19 | filterSize, nbFilters, stride, padding); 20 | std::cout << "Adder2dPlugin Obj Created" << std::endl; 21 | 22 | delete plugin_obj; 23 | 24 | std::cout << "Adder2dPlugin Obj Deleted" << std::endl; 25 | 26 | std::cout << "Creating Adder2dPlugin using c++ is successful" << std::endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /test/TestAdderFilterCudaKernel.cu: -------------------------------------------------------------------------------- 1 | #include "cuda_runtime.h" 2 | #include "device_launch_parameters.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "PluginUtils.h" 9 | 10 | using namespace std; 11 | 12 | 13 | // simple implementation of adder filter 14 | template 15 | __global__ void adderFilter(int in_c, int in_h, int in_w, int k, int stride, int padding, 16 | int out_h, int out_w, const Ftype* input, Ftype* output, const Ftype* weights) 17 | { 18 | int tid_x = threadIdx.x; 19 | int tid_y = threadIdx.y; 20 | int tid = tid_y*out_w + tid_x; 21 | 22 | int filterIdx = blockIdx.x; 23 | 24 | int out_idx = out_h * out_w * filterIdx + tid; 25 | output[out_idx] = 0; 26 | 27 | for(int a=0; ain_h-1 || input_pos_x<0 || input_pos_x>in_w-1) 39 | { 40 | val = 0.0; 41 | } 42 | else 43 | { 44 | val = input[input_idx]; 45 | } 46 | 47 | int weight_idx = filterIdx*in_c*k*k + a*k*k + i*k+ j; 48 | output[out_idx] += fabs(val - weights[weight_idx]); 49 | } 50 | } 51 | } 52 | } 53 | 54 | template 55 | void forwardGpu(int n_filters,int in_c, int in_h, int in_w, int k, int stride, int pad, 56 | int out_h, int out_w, const Dtype* input, Dtype* output, const Dtype* weights) 57 | { 58 | dim3 blkDim(out_w,out_h, 1); 59 | dim3 gridDim(n_filters,1,1); 60 | 61 | adderFilter<<>>(in_c, in_h, in_w, k, stride, pad, out_h, out_w, input, output, weights); 62 | 63 | CUDA_CHECK(cudaDeviceSynchronize()); 64 | } 65 | 66 | 67 | void printMatrix(double * in, int z, int y, int x) 68 | { 69 | cout << "["; 70 | for(int b=0; b < z; b++) 71 | { 72 | cout << "["; 73 | for(int a=0; a