我使用Pybind11,试图将numpy数组传递给c ++到CustomerMaint graph = PXGraph.CreateInstance<CustomerMaint>();
graph.Baccount.Current = graph.Baccount.Search<Customer.baccountID>(pmInstance.BaccountID);
if (graph.Baccount.Current != null)
{
throw new PXRedirectRequiredexception(graph,true,Messages.ViewCustomer) { Mode = PXBaseRedirectException.WindowMode.NewWindow };
}
中,将其乘以2,然后将此std::vector
作为numpy数组返回给python。
我已经迈出了第一步,但第三步却做了一些奇怪的事情。为了将其传回,我使用了:std::vector
奇怪的意思是,Python返回的向量没有正确的尺寸或正确的顺序。
例如,我具有数组:
py::array ret = py::cast(vect_arr);
代码返回:
[[ 0.78114362 0.06873818 1.00364053 0.93029671]
[ 1.50885413 0.38219005 0.87508337 2.01322396]
[ 2.19912915 2.47706644 1.16032292 -0.39204517]]
我已经阅读了文档,但是我必须承认在理解大多数文档时遇到了麻烦。因此,对于此具体示例的任何帮助将不胜感激。提前致谢。
这里是一个示例:
array([[ 1.56228724e+000,3.01770826e+000,4.39825830e+000,5.37804299e+161],[ 1.86059342e+000,4.02644793e+000,-7.84090347e-001,1.38298992e-309],[ 1.75016674e+000,2.32064585e+000,0.00000000e+000,1.01370255e-316]])
以及python代码:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <Python.h>
namespace py = pybind11;
py::module nn = py::module::import("iteration");
py::array nump(py::array arr){
auto arr_obj_prop = arr.request();
//initialize values
double *vals = (double*) arr_obj_prop.ptr;
unsigned int shape_1 = arr_obj_prop.shape[0];
unsigned int shape_2 = arr_obj_prop.shape[1];
std::vector<std::vector <double>> vect_arr( shape_1,std::vector<double> (shape_2));
for(unsigned int i = 0; i < shape_1; i++){
for(unsigned int j = 0; j < shape_2; j++){
vect_arr[i][j] = vals[i*shape_1 + j*shape_2] * 2;
}
}
py::array ret = py::cast(vect_arr); //py::array(vect_arr.size(),vect_arr.data());
return ret;
}
PYBIND11_MODULE(iteration_mod,m) {
m.doc() = "pybind11 module for iterating over generations";
m.def("nump",&nump,"the function which loops over a numpy array");
}
所有这些使用以下命令编译:{{1}} python3 -m pybind11 --includes import numpy as np
import iteration_mod as i_mod
class iteration(object):
def __init__(self):
self.iterator = np.random.normal(0,1,(3,4))
def transform_to_dict(self):
self.dict = {}
for i in range(self.iterator.shape[0]):
self.dict["key_number_{}".format(i)] = self.iterator[i,:]
return self.dict
def iterate_iterator(self):
return i_mod.nump(self.iterator)
def iterate_dict(self):
return i_mod.dict(self)
a = iteration()
print(a.iterator)
print(a.iterate_iterator())