pybind传输list
https://github.com/tdegeus/pybind11_examples/blob/master/01_py-list_cpp-vector/test.pyimport exampleA = [1.,2.,3.,4.]B = example.modify(A)print(B)pybind传输list感觉数据类型必须是单一的某个类型:#include <pybind11/pyb
·
https://github.com/tdegeus/pybind11_examples/blob/master/01_py-list_cpp-vector/test.py
import example
A = [1.,2.,3.,4.]
B = example.modify(A)
print(B)
pybind传输list
感觉数据类型必须是单一的某个类型:
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
// ----------------
// Regular C++ code
// ----------------
// multiply all entries by 2.0
// input: std::vector ([...]) (read only)
// output: std::vector ([...]) (new copy)
std::vector<double> modify(const std::vector<double>& input)
{
std::vector<double> output;
std::transform(
input.begin(),
input.end(),
std::back_inserter(output),
[](double x) -> double { return 2.*x; }
);
// N.B. this is equivalent to (but there are also other ways to do the same)
//
// std::vector<double> output(input.size());
//
// for ( size_t i = 0 ; i < input.size() ; ++i )
// output[i] = 2. * input[i];
return output;
}
// ----------------
// Python interface
// ----------------
namespace py = pybind11;
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("modify", &modify, "Multiply all entries of a list by 2.0");
}
例子2:
import numpy as np
import example
A = [0,1,2,3,4,5]
B = example.multiply(A)
print('input list = ',A)
print('output = ',B)
A = np.arange(10)
B = example.multiply(A)
print('input list = ',A)
print('output = ',B)
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <vector>
// -------------
// pure C++ code
// -------------
std::vector<int> multiply(const std::vector<double>& input)
{
std::vector<int> output(input.size());
for ( size_t i = 0 ; i < input.size() ; ++i )
output[i] = 10*static_cast<int>(input[i]);
return output;
}
// ----------------
// Python interface
// ----------------
namespace py = pybind11;
// wrap C++ function with NumPy array IO
py::array_t<int> py_multiply(py::array_t<double, py::array::c_style | py::array::forcecast> array)
{
// allocate std::vector (to pass to the C++ function)
std::vector<double> array_vec(array.size());
// copy py::array -> std::vector
std::memcpy(array_vec.data(),array.data(),array.size()*sizeof(double));
// call pure C++ function
std::vector<int> result_vec = multiply(array_vec);
// allocate py::array (to pass the result of the C++ function to Python)
auto result = py::array_t<int>(array.size());
auto result_buffer = result.request();
int *result_ptr = (int *) result_buffer.ptr;
// copy std::vector -> py::array
std::memcpy(result_ptr,result_vec.data(),result_vec.size()*sizeof(int));
return result;
}
// wrap as Python module
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("multiply", &py_multiply, "Convert all entries of an 1-D NumPy-array to int and multiply by 10");
}
更多推荐
已为社区贡献17条内容
所有评论(0)