通过 Ctypes 将 std:vector 从 C++ 传递到 Python:获取无意义的值

Passing std:vector from C++ to Python via Ctypes: getting nonsensical values

我试图按照此处的 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() 时,我得到了一个随机数数组。我不确定为什么?

如评论中所述,您的向量是一个局部变量,并在 return 之后从函数中销毁。一种可行的方法是让 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]