我试图遵循程序 https://stackoverflow.com/a/14887649/8408902但我被困住了。我正在尝试通过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
as lib
, 我有:
def q():
lib.returnQ.restype = ndpointer(dtype=ctypes.c_double, shape=(4,))
return lib.returnQ()
然而,当我打电话时q()
在Python中,我得到一个随机数数组。我不知道为什么?
正如评论中提到的,您的向量是一个局部变量,并在从函数返回后被销毁。一种可行的方法是让 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]);
}
Usage:
>>> 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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)