[Cython] [cython-users] beginner question: passing std::vector by reference

Stefan Behnel stefan_ml at behnel.de
Sun Oct 7 08:05:12 CEST 2012


Robert Bradshaw, 03.10.2012 06:55:
> On Tue, Oct 2, 2012 at 12:38 AM, peter aberline wrote:
>> Please excuse my basic question. I'm trying to pass a reference to a
>> std::vector to a function and I'm getting a cpp compilaton error. Here's a
>> minimum example of what I'm doing:
>>
>> test.py:
>>
>> import sys
>>
>> def vectortest(a, idx):
>>     print ('a[idx] is: ' + str(a[idx]))
>>     a[idx] += 1
>>     print ('a[idx] is: ' + str(a[idx]))
>>     return a
>>
>> def run():
>>     lst = range(1, 5)
>>     lstNew = vectortest(lst, 1)
>>
>>     print ('lstNew[1] is :' + str(lstNew[1]))
>>
>> test.pxd
>> import cython
>> from libcpp.vector cimport vector
>>
>> import sys
>>
>> if sys.version_info < (3,):
>>     range = xrange
>>
>> cpdef vector[int] vectortest(vector[int] a, int idx)  # <-- This works fine
>> ('a' is pass by value?)
>>
>> #cpdef vector[int] vectortest(vector[int]& a, int idx) #<-- This generates
>> an 'uninitialised reference' cpp compilation error ('a' is pass by
>> reference?')
>>
>> @cython.locals(lst = vector[int])
>> cpdef run()
>>
>>
>> Compilation error:
>>
>> $/test.cpp: In function ‘PyObject* __pyx_pw_4perf_1vectortest(PyObject*,
>> PyObject*, PyObject*)’:
>> $/test.cpp:640:21: error: ‘__pyx_v_a’ declared as reference but not
>> initialized
> 
> Looks like this was a bug introduced In 0.17.1 and already fixed in master.

In that case, the fix (whatever it was) should also go into the 0.17 branch
so that we can release within a suitable time frame.

Stefan



More information about the cython-devel mailing list