2
votes

According to the Cython documentation ,I write the following cython code as follows:

In [1]:%load_ext Cython
In [2]: %%cython
         from libcpp.vector cimport vector
​         cdef vector[int] *vec_int = new vector[int](10)

After compiling,the ipython generated the following error:

Error compiling Cython file:
------------------------------------------------------------ 
... 
from libcpp.vector cimport vector 
cdef vector[int] *vec_int = new vector[int](10) 
                               ^ 
------------------------------------------------------------
/Users/m/.ipython/cython/_cython_magic_a72abb419ccf1b31db9a1851b522a4bf.pyx:3:32: Operation only allowed in c++

what's wrong with my code?

2

2 Answers

4
votes

You need to tell cython that you are compiling C++ and not C, through the special comment

# distutils: language = c++

adding this after the %%cython block will fix your problem.

2
votes

As an alternative to @romeric's answer, the documentation for ipython Cython magic suggests using

%%cython --cplus

to turn on C++ mode. Help for the command can also be accessed by running %%cython? in the IPython console.

Personally I think there's a lot to be said for using the distutils comment approach, since it links the language with the code that requires it.