using System;
namespace Python.Runtime
{
///
/// Represents a Python (ANSI) string object. See the documentation at
/// PY2: https://docs.python.org/2/c-api/string.html
/// PY3: No Equivalent
/// for details.
///
///
/// 2011-01-29: ...Then why does the string constructor call PyUnicode_FromUnicode()???
///
public class PyString : PySequence
{
///
/// PyString Constructor
///
///
/// Creates a new PyString from an existing object reference. Note
/// that the instance assumes ownership of the object reference.
/// The object reference is not checked for type-correctness.
///
public PyString(IntPtr ptr) : base(ptr)
{
}
private static IntPtr FromObject(PyObject o)
{
if (o == null || !IsStringType(o))
{
throw new ArgumentException("object is not a string");
}
Runtime.XIncref(o.obj);
return o.obj;
}
///
/// PyString Constructor
///
///
/// Copy constructor - obtain a PyString from a generic PyObject.
/// An ArgumentException will be thrown if the given object is not
/// a Python string object.
///
public PyString(PyObject o) : base(FromObject(o))
{
}
private static IntPtr FromString(string s)
{
IntPtr val = Runtime.PyUnicode_FromUnicode(s, s.Length);
PythonException.ThrowIfIsNull(val);
return val;
}
///
/// PyString Constructor
///
///
/// Creates a Python string from a managed string.
///
public PyString(string s) : base(FromString(s))
{
}
///
/// IsStringType Method
///
///
/// Returns true if the given object is a Python string.
///
public static bool IsStringType(PyObject value)
{
return Runtime.PyString_Check(value.obj);
}
}
}