C++ Vector如何转成numpy array
时间: 2024-01-27 09:02:39 浏览: 31
在Python中,可以使用NumPy库来处理数组和矩阵。要将C++中的向量转换为NumPy数组,可以使用以下步骤:
1. 在C++代码中,将向量转换为C数组,然后将其传递给Python。
2. 在Python中,使用NumPy库中的`array`函数将C数组转换为NumPy数组。
以下是示例代码:
C++代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
extern "C" {
void get_data(int* data, int size) {
vector<int> vec(size);
for (int i = 0; i < size; i++) {
vec[i] = i;
}
copy(vec.begin(), vec.end(), data);
}
}
```
Python代码:
```python
import numpy as np
import ctypes
# Load the shared library
lib = ctypes.CDLL('./libexample.so')
# Define the C function signature
get_data = lib.get_data
get_data.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int]
# Call the C function
size = 10
data = (ctypes.c_int * size)()
get_data(data, size)
# Convert the C array to NumPy array
np_data = np.ctypeslib.as_array(data, shape=(size,))
print(np_data)
```
输出:
```
[0 1 2 3 4 5 6 7 8 9]
```
在Python中,可以使用`np.ctypeslib.as_array`函数将C数组转换为NumPy数组。该函数需要两个参数:C数组指针和数组形状。在本例中,使用`shape=(size,)`将一维数组转换为NumPy数组。