I have a C++ function that receives an int array and I'm making a python wrapper for it with ctypes and numpy. Here is a minimal example:
copy.cpp
#include <vector>
extern "C" std::vector<int>* copy_vec(int* array, int size){
std::vector<int>* vec = new std::vector<int>(size);
for (int i=0; i<size; i++){
vec->push_back(array[i]);
}
return vec;
}
copy.py
import ctypes as ct
import numpy as np
INT_POINTER = ct.POINTER(ct.c_int)
_lib = ct.cdll.LoadLibrary('./libcopy.dll')
_lib.copy_vec.argtypes = [INT_POINTER, ct.c_int]
def copy(nums):
size = len(nums)
nums_c = np.array(nums).ctypes.data_as(INT_POINTER)
vector = _lib.copy_vec(nums_c, size)
return vector
array =[12]*1000000
copy(array)
This produces the following error message:
---------------------------------------------------------------------------
WindowsError Traceback (most recent call last)
<ipython-input-2-752101759a61> in <module>()
1 array =[12]*1000000
----> 2 copy(array)
<ipython-input-1-f18316d64ae3> in copy(nums)
10 size = len(nums)
11 nums_c = np.array(nums).ctypes.data_as(INT_POINTER)
---> 12 vector = _lib.copy_vec(nums_c, size)
13
14 return vector
WindowsError: exception: access violation reading 0x08724020
This code works for small arrays like array =[12]*100
, but fails when using big arrays.