将 std::vector<int> 从原始内存转换为数组



我正在使用ctypes为c ++库开发python接口。我知道不建议这样做,但我无法修改有问题的 dll,所以一切都必须在 python 包装器中进行。

假设我们将此函数编译到 dll 中:

vector<int> vectortest() {
return { 1, 2, 3 };
}

我的python脚本看起来像这样:

# [ setup dll ... ]
VectorTest.restype = ct.c_ulonglong * 32 
# set the return type to 64bit unsigned 
# integer array with 32 elements (this is just for debugging atm.)
vec = VectorTest() # call the c++ function, vec should now contain the returned memory
for i in range(0, 32): # print all the values
print(vec[i])
print('diff1', vec[3] - vec[0]) # this value never changes
print('diff2', vec[15] - vec[4]) # this value never changes

现在我只是转储返回的内存以尝试找到 begin(( 和 end(( 指针,因为从技术上讲,这些是我找到数组值所需要的。

下面是一个输出示例:

754548928240
2850274634992
0
754548928400
1545446976
0
0
140731499719200
0
165212429600621
0
0
0
0
0
1545365980
2850237907016
2850274763904
2850273274168
0
751619281153
0
2850273493592
0
2847563317248
0
2850273493592
140731499719200
2850273274168
754548929040
0
2850238680016
diff1 160
diff2 -80996

底部的 diff 值都与向量大小无关,因此第一个和第四个元素不能是开始和结束指针。我还尝试取消引用并打印位于内存位置的值,但从未找到值 1、2、3。

我要问的是:

  • std::vector 到底是如何存储在内存中的?

  • 有没有更好的方法可以解决这个问题,不需要修改 C++ DLL?

YiFei 建议创建另一个环绕向量相关函数的 C++ dll,然后将 python 脚本绑定到该 dll。我会继续这样做,所以我认为这是问题的解决方案。感谢所有参与其中的人!

编辑:此解决方案已实施并完美运行。

最新更新