开发者

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. N开发者_Go百科ext 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜