C language string converted to Python string method

  • 2020-10-31 21:53:40
  • OfStack

The problem

How do I convert a string in C to an Python byte or 1 string object?

The solution

The C string USES 1 pair char * and int You need to decide whether the string should be represented as a raw byte string or an Unicode string. The byte objects can be used as follows Py_BuildValue() To build:


char *s; /* Pointer to C string data */
int len; /* Length of data */

/* Make a bytes object */
PyObject *obj = Py_BuildValue("y#", s, len);

If you want to create an Unicode string, and you know that s refers to the data encoded by UTF-8, you can use the following method:


PyObject *obj = Py_BuildValue("s#", s, len);

if s If you use other encoding methods, you can use them as below PyUnicode_Decode() To build a string:


PyObject *obj = PyUnicode_Decode(s, len, "encoding", "errors");

/* Examples /*
obj = PyUnicode_Decode(s, len, "latin-1", "strict");
obj = PyUnicode_Decode(s, len, "ascii", "ignore");

If you have exactly one wchar_t *, len There are several options for representing wide strings. First you can use it Py_BuildValue() :


wchar_t *w; /* Wide character string */
int len; /* Length */

PyObject *obj = Py_BuildValue("u#", w, len);

Plus, you can use it PyUnicode_FromWideChar() :


PyObject *obj = PyUnicode_FromWideChar(w, len);

For wide strings, character data is not parsed -- it is assumed to be the original Unicode encoded pointer, which can be converted directly to Python.

discuss

Converting a string from C to Python follows the same principles as I/O. That is, the data from C must be explicitly decoded into a string based on one of the decoders. The usual encoding formats include ASCII, Latin-1, and UTF-8. If you're not sure how to encode it or if the data is in base 2, you might want to encode the string as bytes. When constructing an object, Python usually copies the string data you provide. If necessary, you need to release the C string later. Also, to make your program more robust, you should use both a pointer and a size value, rather than relying on NULL ending data to create strings.

That's how to convert C strings to Python strings. For more information on converting C strings to Python strings, check out the other articles on this site!


Related articles: