我试图在此处遵循procedure,但被困住了。我试图将std:vector
从我的C ++代码(包装在extern C
中)传递给Python。这就是我所拥有的:
extern 'C' {
double* returnQ() {
std::vector<double> v = {7.5, 5.5, 16.5, 8.5};
std::cout<<"Print first element:"<<vec[0]<<std::endl;
return v.data(); }
}
这是我的python代码。通过ctypes
作为lib
加载库之后,我有:
def q():
lib.returnQ.restype = ndpointer(dtype=ctypes.c_double, shape=(4,))
return lib.returnQ()
但是,当我在Python中调用q()
时,我得到了一个随机数数组。我不确定为什么吗?
答案 0 :(得分:1)
如注释中所述,向量是局部变量,从函数返回后销毁。一种有效的方法是让Python管理内存并将数据复制到其中。
test.cpp
#include <vector>
#include <cstring>
#define API __declspec(dllexport) // Windows-specific export
// Must pass double[4] array...
extern "C" API void returnQ(double* data) {
std::vector<double> v = {7.5, 5.5, 16.5, 8.5};
// Of course, you could write directly to "data" without the vector...
std::memcpy(data,v.data(),v.size() * sizeof v[0]);
}
用法:
>>> from ctypes import *
>>> dll = CDLL('test')
>>> dll.returnQ.argtypes = POINTER(c_double),
>>> dll.returnQ.restype = None
>>> data = (c_double * 4)() # equivalent to C++ double[4]
>>> dll.returnQ(data)
>>> list(data)
[7.5, 5.5, 16.5, 8.5]