1

I'm trying to export some C++ functions into python, and it's working pretty well most of the time, but I'm having issues when a function takes more than on string in parameters, the first one is always ok, but the other ones are always gibberish.

C++ code:

#include <Python.h>

#include <iostream>

PyObject* wrap_one_string(PyObject *self, PyObject *args)
{
    char* str;
    if (!PyArg_ParseTuple(args,"s:wrap_one_string",&str))
    {
        return nullptr;
    }
    std::cout << str << std::endl;
    return Py_None;
}

PyObject* wrap_two_string(PyObject *self, PyObject *args)
{
    char* str1, str2;
    if (!PyArg_ParseTuple(args,"ss:wrap_one_string", &str1, &str2))
    {
        return nullptr;
    }
    std::cout << str1 << std::endl << str2 << std::endl;
    return Py_None;
}

static PyMethodDef exampleMethods[] = {
    { "one_string", wrap_one_string, METH_VARARGS, nullptr },
    { "two_string", wrap_two_string, METH_VARARGS, nullptr },
    { nullptr, nullptr, 0, nullptr}
};

extern "C"
{

    __declspec(dllexport)
    void initexample()
    {
         PyObject *m;
         m = Py_InitModule("example", exampleMethods);
    }

}

python code:

import example

example.one_string("ab")
example.two_string("abcd", "efgh")

And the result is:

ab
abcd
È

The second string parameter is always a weird character. Any idea where this might come from?

Thanks

3
  • 1
    did you try example.two_string(("abcd","efgh")) or example.two_string(["abcd","efgh"]) ? Commented Sep 9, 2015 at 13:28
  • Hmmm, still the same with a tuple, but it seems to work with a list, also I have to use a different method to parse the list... Commented Sep 9, 2015 at 13:40
  • That got me thinking, when I access the second string with macros for tuple object, I can get it properly: PyString_AsString(PyTuple_GET_ITEM(args, 1)) Commented Sep 9, 2015 at 13:44

2 Answers 2

3

Ah, nevermind, dumb mistake from my part

char* str1, str2;

should be

char* str1, *str2;

Too bad it compiled, though it did give an error using

str2 = PyString_AsString(PyTuple_GET_ITEM(args, 1))

to access the second string.

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

1 Comment

That's why some code conventions require * and & to be bound to variable name, not type :) Being written like char *str1, str2;, the mistake is much more obvious.
1

One small note, remember to Py_INCREF(Py_None); before returning Py_None, as stated in the reference [https://docs.python.org/2/extending/extending.html#back-to-the-example] Or use Py_RETURN_NONE macro [https://docs.python.org/2/c-api/none.html#c.Py_RETURN_NONE]

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.