代码之家  ›  专栏  ›  技术社区  ›  tryingtosolve

传递STD:通过cType从C++到python的向量:获取无意义的值

  •  0
  • tryingtosolve  · 技术社区  · 7 年前

    我试着跟着 procedure 但我被卡住了。我想通过一个 std:vector 从我的C++代码中 extern C

    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()
    

    但是,当我打电话给 q()

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mark Tolonen    7 年前

    如注释中所述,向量是一个局部变量,从函数返回后会被销毁。一种有效的方法是让Python管理内存并将数据复制到其中。

    #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]