2

I have a c++ map that I need to send to a python script for processing. I figured that I should put it in a PyDict and then send it. The problem s that my script doesn't receive it correctly

my c++

#include <Python.h> #include <string> int main(int argc, char *argv[]) { Py_Initialize(); PyObject *import, *attr, *instance, *methodcall, *arg, *tuple; PySys_SetPath("./py/"); import = PyImport_ImportModule("class_test"); attr = PyObject_GetAttrString(import, "TestMap"); arg = PyString_FromString("arg from first"); tuple = PyTuple_Pack(1, arg); instance = PyInstance_New(attr, tuple, NULL); PyObject *d = PyDict_New(); PyDict_SetItemString(d, "k", PyInt_FromLong(3000)) ? printf("seting item failed\n") : printf("seting item succeeded\n"); methodcall = PyObject_CallMethod(instance, "hello", "s", d); Py_DECREF(instance); Py_Finalize(); return 0; } 

and my simple script

class TestMap(CLBase): def __init__(self, c): self.c = c pass def hello(self, s): print "From python script" print s 

the output is

seting item succeeded From python script ☺ 

so rather than printing the dictionary something like {"k":3000} it prints a smiley face

I would really appreciate an answer using the default python API (using python.h) not any other library

1 Answer 1

2
methodcall = PyObject_CallMethod(instance, "hello", "s", d); 

With the "s" you're telling it that the argument is a char* but it's actually a dictionary (a PyObject*). If you use "O" it will be correctly interpreted as a PyObject*. The format string of PyObject_CallMethod is interpreted as per Py_BuildValue and so is documented here.

The smiley face is just a re-interpretation of whatever is in the memory of the dict as a string.


Other than that you should be checking the return values of the Python API functions (NULL usually indicates an error) and there look to be some PyObjects that you never decref, so you're leaking memory.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.