4

How can I get a char* from a PyObject which points to a string. For example, this is the python script,

Test.Connect("272.22.20.65", 1234)

and this is the C++ code,

static PyObject* Connect(PyObject *self, PyObject *args)
{
    PyObject* pIP;
    PyObject* pPort;

    if (!PyArg_UnpackTuple(args, "Connect", 2, 2, &pIP, &pPort)) 
    {
        return NULL;
    }

    const char* zIP = GetAsString(pIP);
    long iPort      = PyLong_AsLong(pPort);

I want to get that IP address as a char* (GetAsString is a dummy function :D ). Please note that I'm using Python 3.1.

P.S. I don't think this question got the correct answer , since there is no PyStringObject or PyString_AsString in Python 3. Isn't it ?

2
  • @Sven Marnach. it is str. But there is no way of getting char* from PyUnicode_*. Am I wrong ? Commented Mar 27, 2012 at 19:41
  • lol...where is Sven Marnach ? When I replied you, your comment was missing Commented Mar 27, 2012 at 19:43

2 Answers 2

5

First you encode it, then you retrieve it. Don't forget to decref the temporary.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer, but it is not working. PyBytes_AsString is returing a NULL. (in a simplify way this is how I used it, PyBytes_AsString(PyUnicode_AsUTF8String(pObject)) )
@Sven Marnach. Thanks for the point. I'm confused with python3, with python2x it is straightforward, isn't it.
Calling the two functions together like that will result in a memory leak.
I simplified it for commenting, it is like this. PyObject* pStrObj = PyUnicode_AsUTF8String(pObject); char* zStr = PyBytes_AsString(pStrObj); char* zStrDup = strdup(zStr); Py_DECREF(pStrObj); Hope I did it in correct way.
0

Here is my portable recipe for it, which makes use the default encoding, where that is applicable. It assumes you start with a PyObject*, named o. If you still have your input tuple from the function call, you can skip the first 2 lines.

PyObject* args = Py_BuildValue("(O)", o);
/* Py_DECREF(o); if o is not borrowed */
if (!args) return 0;
const char* s = 0;
if (!PyArg_ParseTuple(args, "s", &s)) {
  Py_DECREF(args);
  return 0;
}

/* s now points to a const char* - use it, delete args when done */

Py_DECREF(args);

PS: I have not tested it, but it should work with older versions of Python as well. There is nothing on it which is version specific.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.