python - Writing Cython class with template? - Stack Overflow

admin2025-04-29  3

Background: I am fairly new to the Cython, and I am not experienced with C++. I am aware of C++ template feature, and I am not really sure how to write a proper class in C++.

Objective: I am trying to write a class in Cython that mimics behaviors of a dictionary. But, instead of strings, I want to use enum, or other user-defined types as keys.

Previous Research: Based on 1, 2, and 3, it seems like I can use template in Cython classes. But I was not able to find any other documentation on this.

My Attempts: Given these, what I wrote is just a simple modification to a Cython class I wrote without template, which reads,

cdef class ScalarDict[T]:
    cdef:
        public long N
        public long ndata
        size_t size
        long __current_buffer_len
        T * __keys
        double ** __values

    def __cinit__(self, long ndata, long N=4):
        cdef long i
        self.__current_buffer_len = N
        self.N = 0
        self.ndata = ndata
        self.size = ndata*sizeof(double)
        self.__keys = <T *>malloc(self.__current_buffer_len*sizeof(T))
        self.__values = <double **>malloc(self.__current_buffer_len*sizeof(double *))
        
    def __dealloc__(self):
        cdef long i
        if self.N > 0:
            for i in range(self.N):
                if self.__values[i] != NULL:
                    free(self.__values[i])
        if self.__values != NULL:
            free(self.__values)
        if self.__keys != NULL:
            free(self.__keys)

    # other methods...

But this fails to compile, with error messages including Name options only allowed for 'public', 'api', or 'extern' C class and Expected 'object', 'type' or 'check_size' on the line with cdef class ScalarDict[T]:.

What is the correct way of doing this? Or, is it not possible?

转载请注明原文地址:http://anycun.com/QandA/1745941765a91430.html