简体   繁体   中英

Python Unicode object and C API ( retrieving char* from pyunicode objects )

I am currently binding all of my C++ engine classes to python for game play scripting purposes. The latest challenge is that when say you make a variable in the script a string such as

string = 'hello world'

this becomes a PyUnicodeObject. Next we want to call a function on this object in the script from a bound C side function. PrintToLog( string ), as an example lets say this c-function is as such

void PrintToLog( const char * thisString )
{
   //file IO stuff as expected
   myLog << thisString;
   //more stuff involving fileIO
}

So my binding needs to extract a char * from the PyUnicodeObject which will be passed at first by the python to my generic function handler, which in turn will extract and covert the pyobjects to the proper c-side type and pass it to my function.

The only function I can find extracts a wchar_t*... Is there anyway to get the ascii representation since we will only be using the ascii character set.

EDIT: I am using Python 3.2 where all strings are unicode

I was facing a similar problem with Python3. I solved it as follows.

If you have a PyUnicodeObject "mystring", do something like

PyObject * ascii_mystring=PyUnicode_AsASCIIString(mystring);
PrintToLog(PyBytes_AsString(ascii_mystring));
Py_DECREF(ascii_mystring);

PyBytes is explained here .

I believe the function you're looking for is PyUnicode_AsASCIIString . This will give you a non-unicode (ASCII) python string. And then you can take the normal approach for extracting a char* from that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM