问题
Say I have a .h file with the following code:
class MyClass
{
public:
int Attribute1;
int Attribute2;
MyClass(){};
virtual ~MyClass(){};
virtual void Method1(string var1);
virtual float Method2(float var2);
};
And a related .pyx file with:
cdef class PyClass:
cdef MyClass *classptr
[standard __cinit__ and __dealloc__ declarations ]
cdef int Attribute1;
def Method1(self, var1):
self.classptr.Method1(var1)
... and pxd file with:
cdef extern from "mycode.h":
cdef cppclass MyClass:
MyClass() except +
int Attribute1
void Method1(string)
And I use a setup.py to create a .so library to import in a python module.
Note that even though MyClass::Method2 and MyClass::Attribute2 exist in c++, I don't mention them in Cython, so they won't be visible in the .so library. Maybe I did so because they're indirectly used by MyClass::Method1(), or just because I don't plan to invoke them in the python code.
Is this a bad practice likely to cause a problem/weird behavior? If so, why?
回答1:
cdef class PyClass:
cdef MyClass *classptr
# ...
cdef int Attribute1;
Attribute1
doesn't do what you think. It's a separate value stored as part of PyClass
and has nothing to do with the Attribute1
in classptr
. You probably want to write a property instead.
However, to answer your question:
Yes, it's fine for you to only wrap the specific functions you're interested in. Cython doesn't need to know all the details of your C++ classes - it only needs to know enough details to generate valid C++ code using them. A few quick examples of things it's useful to omit:
Templates. For example
std::string
is really a template typedef, but it may not be necessarily for a Cython wrapper to know this, or for optional allocator template types, or for numeric template types which Cython doesn't really support.Complicated inheritance hierarchies: doesn't matter if the functions you care about actually come from a base-class. Just wrap the derived class you're using.
Interfaces that return other classes - because then you'd need to wrap the second class (which might expose a third class...).
There really is no consequence beyond not being able to call the code you haven't wrapped from python. Cython's C++ support is (and will likely always be) somewhat incomplete and it's often necessary to give it a simplified C++ interface to get anything done.
来源:https://stackoverflow.com/questions/58842108/in-c-cython-it-possible-to-only-declare-relevant-attributes-to-be-visible-in-p