std::vector を返す C++ 関数があり、それを Python で使用したいので、C numpy API を使用しています。
static PyObject *
py_integrate(PyObject *self, PyObject *args){
...
std::vector<double> integral;
cpp_function(integral); // This changes integral
npy_intp size = {integral.size()};
PyObject *out = PyArray_SimpleNewFromData(1, &size, NPY_DOUBLE, &(integral[0]));
return out;
}
Pythonから呼び出す方法は次のとおりです。
import matplotlib.pyplot as plt
a = py_integrate(parameters)
print a
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(a)
print a
何が起こるか: 最初の印刷は問題なく、値は正しいです。しかし、私がプロットa
すると、そうではありません。1E-308 1E-308 ...
2 番目のプリントでは、または0 0 0 ...
初期化されていないメモリのような非常に奇妙な値が表示されます。最初の印刷がOKな理由がわかりません。
部分的な解決策 (機能しない):
static void DeleteVector(void *ptr)
{
std::cout << "Delete" << std::endl;
vector * v = static_cast<std::vector<double> * >(ptr);
delete v;
return;
}
static PyObject *
cppfunction(PyObject *self, PyObject *args)
{
std::vector<double> *vector = new std::vector<double>();
vector->push_back(1.);
PyObject *py_integral = PyCObject_FromVoidPtr(vector, DeleteVector);
npy_intp size = {vector->size()};
PyArrayObject *out;
((PyArrayObject*) out)->base = py_integral;
return (PyObject*)(out);
}