[英]How do I check input variable validity from a Python extension?
I have a Python extension written in C++ that expects a bytearray as the first parameter. 我有一个用C ++编写的Python扩展,期望将bytearray作为第一个参数。 It works correctly but if I pass something else from Python like a string or a number, I get a segmentation fault.
它可以正常工作,但是如果我从Python传递其他内容(例如字符串或数字),则会出现分段错误。 How do I check if the input is really a bytearray and then raise an Exception if it's something else?
如何检查输入是否确实是字节数组,然后在其他情况下引发异常?
This should help: http://docs.python.org/2/faq/extending.html#id8 这应该会有所帮助: http : //docs.python.org/2/faq/extending.html#id8
To test the type of an object, first make sure it isn't
NULL
, and then usePyString_Check()
,PyTuple_Check()
,PyList_Check()
, etc.为了测试的对象的类型,首先要确保它不是
NULL
,然后用PyString_Check()
PyTuple_Check()
PyList_Check()
等等。
Specifically, it looks like you want this: http://docs.python.org/2/c-api/bytearray.html#type-check-macros 具体来说,您看起来像这样: http : //docs.python.org/2/c-api/bytearray.html#type-check-macros
int PyByteArray_Check(PyObject *o)
Return true if the object o is a bytearray object or an instance of a subtype of the bytearray type.
如果对象o是字节数组对象或字节数组类型的子类型的实例,则返回true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.