Thomas Johnson
Thomas Johnson

Reputation: 11718

operator= in Cython cppclass

How can I tell Cython that my C++ class has overloaded operator=? I tried:

cdef extern from "my_source.H":
  cdef cppclass MyStatus:
    void operator=(const char* status)

cdef public void setStatus(MyStatus& status):
  status = "FOO"

but Cython either complains "Assignment to reference status" or (if I make status a non-reference) constructs a python object out of the string "FOO" and then tries to assign the python object to status.

Upvotes: 1

Views: 360

Answers (1)

ead
ead

Reputation: 34367

The problem in your code is, that for Cython "FOO" is a Python-object. For expressions like

char *s = "FOO"

Cython is clever enough to understand, what you want and automatically interprets "FOO" as char *.

However, Cython doesn't really "understand"/interpret the signatures of wrapped c++-functions (for that it must be a c++-compiler) and thus cannot know, that you want "FOO" be a char *.

Thus you have to help Cython, for example:

status = <const char *>"FOO"

You also have to work around the problem with reference, for example via:

cdef public void setStatus(MyStatus *status):
    status[0] = <const char *>"FOO"

or if you want to have keep the signature of the function intact:

cdef public void setStatus(MyStatus& status):
     cdef MyStatus * as_ptr = &status 
     as_ptr[0] = <const char *>"FOO"

I'm not completely sure the problem with the assigment to reference isn't a bug.

Another observation: the assigment operators aren't part of the "official" wrap of the standard containers, see here or here.

Upvotes: 1

Related Questions