1

In the following code, I am trying to pack two null-terminated C strings (char pointers) into a Python tuple.

printf("word1 = '%s', word2 = '%s'\n", words1->wordArray[i], words2->wordArray[i]);
cmpArgs = Py_BuildValue("ss", words1->wordArray[i], words2->wordArray[i]);
printf("%s\n", PyString_AsString(PyTuple_GetItem(cmpArgs, 0)));

This produces output like:

word1 = '20', word2 = '20'
i┓

Why is the string different in the tuple than outside it? What am I doing wrong? Also, do I need to worry about incrementing and decrementing the reference count of this tuple? (I am creating it to pass to a Python function passed to C as a PyObject*)

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
dpitch40
  • 2,621
  • 7
  • 31
  • 44
  • 1
    Your code looks correct. Did you `#include `? Are you compiling with all the warnings turned on (`-Wall` with gcc)? Sometimes forgetting an `#include` can cause the generated code to incorrectly pass pointer arguments to variadic functions such as `Py_BuildValue`. Turning on warnings helps to catch that kind of bug (and many others). – user4815162342 Nov 01 '12 at 18:03
  • 1
    Also, does it help if you replace `Py_BuildValue(...)` with `cmpArgs = PyTuple_New(2); PyTuple_SetItem(cmpArgs, 0, PyString_FromString(words1->wordArray[i]); PyTuple_SetItem(cmpArgs, 1, PyString_FromString(words2->wordArray[i]);`? If that helps, it points to `Py_BuildValue` being borked, likely due to a missing or broken header. – user4815162342 Nov 01 '12 at 18:05
  • What headers could I need besides ? (Which I am including) Trying your code messes up the strings horribly and causes it to go into an infinite loop. Could I be counting references incorrectly? – dpitch40 Nov 01 '12 at 18:45

1 Answers1

1

I think I got it--I was previously storing the words in a weird way using stack space. I started manually allocating space on the heap for them which seems to have fixed it.

dpitch40
  • 2,621
  • 7
  • 31
  • 44