C++ embedded python PyArg_ParseTuple fails with string args - c++

I'm trying to add embedded python to a OpenGL/SDL application.
So far everything works fine, like entering a string via SDL keyboard events and executing it with the embedded python interpreter.
I'm now into adding functions to call C/C++ functions like
void set_iterations(int c);
is invoked on the python interpreter with
>>> test.iterations(23)
The parsing of the integer parameter works like charm
static PyObject* test_iterations(PyObject *self, PyObject *args) {
int iterations;
PyArg_ParseTuple(args,"i",&iterations);
set_iterations(iterations);
return Py_None;
}
But when I try this: >>> test.addignore('something')
static PyObject* test_addignore(PyObject *self, PyObject *args) {
char* ignorestring;
//PyArg_ParseTuple(args,"s",ignorestring);
PyArg_ParseTuple(args,"s",&ignorestring);
add_global_ignore(ignorestring); // C function
return Py_None;
}
Python gives me this error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data
The string should be UTF-8, as SDL is set to grab UNICODE from the keyboard, and everything else works perfectly.
Does anyone have an idea on what I might be doing wrong here?
I also inspected the args object passed to the function with
std::string args_str;
PyObject* repr = PyObject_Repr(args);
if (repr != NULL) {
args_str = PyBytes_AsString(PyUnicode_AsEncodedString(repr, "utf-8", "Error"));
Py_DECREF(repr);
}
std::cout << args_str << "\n";
And it gives me this: ('somestring',)
Solution:
The error pointed out by rodrigo, was originally causing be believe that my debug code that should print the resulting string as PyObject was wrong. But the problem was that I was passing the parser the wrong pointer, leading to said undefined behaviour in the memory and therefore leading me to believe the parser was the problem.
The occurring last parser error was then the debug output itself, which was pointing to the wrong memory address.
Thanks rodrigo, since your answer lead to solving the problem: accepted. Thank you for your help and patience.

Try:
static PyObject* test_addignore(PyObject *self, PyObject *args) {
char* ignorestring;
if (!PyArg_ParseTuple(args,"s", &ignorestring)) //Note the &
return NULL; //Never ignore errors
add_global_ignore(ignorestring);
Py_RETURN_NONE; //Always use helper macros
}

Related

Passed string become empty in gdb?

I have the following code:
CrowdSim::Simulation my_simulation;
void printstring(std::string filename)
{
std::cerr<<"filename= " <<filename<<std::endl;
}
int main(int argc, char* argv[])
{
std::vector<std::string> tokens;
std::string filename = "";
if(argc > 1)
{
std::string args(argv[1]);
split(tokens, args, is_any_of("\"="), token_compress_on);
filename = tokens.at(1);
}
my_simulation = CrowdSim::Simulation();
printstring(filename);
I run the program with the following
./CrowdSim -filename="Layout/layout_1"
Within gdb, I put a breakpoint right before printstring(filename). When hitting this breakpoint, I execute print filename, and the output is "Layout/layout_1". Immediately after entering printstring (stepping in with step), I print filename and the result is "".
However, if I actually let the next line run, the output is fine: it prints filename= Layout/layout_1. Is this some sort of gdb error? It's making it very hard to debug without using a ton of cerr statements. What could be causing this?
Additionally, if I comment out all lines involving my_simulation (so that it never gets initialized and I never use it) I get an error upon stepping into printstring:
printstring (filename=Traceback (most recent call last):
File "/usr/share/gdb/python/libstdcxx/v6/printers.py", line 469, in to_string
return self.val['_M_dataplus']['_M_p'].string (encoding, length = len)
RuntimeError: Error reading string from inferior: Input/output error
) at Source/main.cc:13
I also tested this with a program which contains only the above main and printstring functions, with no references to any other objects. The above error still occurs.
Can anyone explain either of these errors to me? Also, somewhat related, in c++, does the line CrowdSim::Simulation my_simulationautomatically call the constructor, so that I no longer need the line my_simulation = ...? In Java, declaring a variable doesn't construct it (as far as I know), so both lines are usually necessary (I think).

Build error in embedding python-(where I import the file)

I am a beginner in python and have an intermediate level knowledge about C++.
I am trying to embed python code in c++. However, I get a build error and with my current level of knowledge I am unable to troubleshoot it.Kindly help me in this regard.
Following is the code.
#include <iostream>
using namespace std;
#include <Python.h>
int main()
{
cout<<"Calling Python to find the sum of 2 and 2";
// Initialize the Python interpreter.
Py_Initialize();
// Create some Python objects that will later be assigned values.
PyObject *pName,*pModule, *pDict, *pFunc, *pArgs, *pValue;
// Convert the file name to a Python string.
pName = PyString_FromString("Sample.py"); // Import the file as a Python module.
pModule = PyImport_Import(pName);
// Create a dictionary for the contents of the module.
pDict = PyModule_GetDict(pModule);
// Get the add method from the dictionary.
pFunc = PyDict_GetItemString(pDict, "add");
// Create a Python tuple to hold the arguments to the method.
pArgs = PyTuple_New(2);
// Convert 2 to a Python integer.
pValue = PyInt_FromLong(2);
// Set the Python int as the first and second arguments to the method.
PyTuple_SetItem(pArgs, 0, pValue);
PyTuple_SetItem(pArgs, 1, pValue);
// Call the function with the arguments.
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
// Print a message if calling the method failed.
if(pResult == NULL)
cout<<"Calling the add method failed.\n";
// Convert the result to a long from a Python object.
long result = PyInt_AsLong(pResult);
// Destroy the Python interpreter.
Py_Finalize(); // Print the result.
cout<<"The result is"<<result;
cout<<"check";
return 0;
}
I get the following error:
Unhandled exception at 0x00000000 in pytest.exe: 0xC0000005: Access violation.
and the build breaks at the line pModule = PyImport_Import(pName);
the file Sample.py has the contents:
# Returns the sum of two numbers.
def add(a, b):
return a+b
I am using python 2.7 and VS2010.I have created a win32 console project for this and I am building in release mode.I have copied the file Sample.py to the project folder.
I cannot figure out what's causing the build to crash.Kindly help.
Firstly, indent your code, MSVC even has an option to do it automatically! After all, you want people here to read it, so go and clean that up. Then, don't declare variables without initializing them in C++. This makes it clear from where on you can use them. Lastly, whenever you call a function, check its results for errors. By default, just throw std::runtime_error("foo() failed"); on errors. More elaborate, you could try to retrieve and add error information from Python.
Now, your immediate error is the use of a null pointer, which you would have avoided if you had checked returnvalues. After writing the code to correctly detect that error, the next thing I'd look at is the missing initialization of the Python interpreter. You already have a comment in place, but comments don't count. I guess that if you had implemented proper error handling, Python would also have told you about the missing initialization.

python with c++ using ctypes

As I'm still new to this, I'm facing some problems, here's my C++ code:
#include <python.h>
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT PyObject *Add(PyObject *pSelf, PyObject *pArgs)
{
int s,d;
if(!PyArg_ParseTuple(pArgs, "ii" , &s, &d))
{
PyErr_SetString(PyExc_TypeError,
"Add() invalid parameter");
return NULL;
}
return Py_BuildValue("i", s + d);
}
And the Python code:
import ctypes
MyDll = ctypes.cdll.LoadLibrary(r"PyToCppTest.dll")
jj = MyDll.Add(1,2)
I get an error when I run the above Python code:
OSError: exception: access violation reading 0x000000000000000A
I want to pass the data, without converting it, from Python to C++, then convert it inside C++.
Use either an extension or ctypes; you're not supposed to call your extension through ctypes. The point of extensions is to be able to create modules that look native to people using them from Python. ctypes serves to call C code that was written completely oblivious of Python.
There are a few things that are wrong with your code. First and foremost, the proper include is:
#include <Python.h>
Note the capital P. You're probably on Windows, but this wouldn't work on Linux without the capital P.
Also, I don't see the point of the *pSelf pointer in your function declaration, you should get rid of it:
PyObject *Add(PyObject *pArgs)
Now, your main problem is this:
MyDll.Add(1,2)
...does not call MyDll.Add with a tuple. It calls it with two integer arguments, 1 and 2. If you want to pass a tuple, you'd do:
MyDll.Add((1,2))
However, Python's ctypes won't know what to do with this (it normally accepts integer arguments), so you'll need to tell it that Add actually wants a tuple, and returns a Python object:
import ctypes
MyDll = ctypes.cdll.LoadLibrary("PyToCppTest.dll")
MyCFunc = ctypes.PYFUNCTYPE(
ctypes.py_object, # return val: a python object
ctypes.py_object # argument 1: a tuple
)
MyFunc = MyCFunc(('Add', MyDll))
jj = MyFunc((1,2))

Call C++ function from Python by reference

I have successfully wrapped my C++ code with SWIG and it loads fine into Python. I am using the Olena library for image processing.
However, I don't know how to call my functions that require a pointer to an image!
For instance, my function for eroding an image is prototyped as follows:
mln::image2d<mln::value::int_u8> imErossion(
const mln::image2d<mln::value::int_u8> *img, int size, int nbh
);
Result of running my code within Python:
from swilena import *
from algol import *
image = image2d_int_u8
ima = image.load("micro24_20060309_grad_mod.pgm")
eroded_ima = imErossion(ima,1,8)
>>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: in method 'imErossion', argument 1 of type
'mln::image2d<mln::value::int_u8 > const *'
I have been looking all around the web to try and solve this myself, but it turns to be harder than I expected.
I'm not sure how to pass a pointer from Python -- the equivalent of this C++ code:
eroded_ima = imErossion(&ima,1,8)
I checked with my professor at university, and we decided it would be better to implemente a function that would return the pointer to the image when this one was loaded and declared it global:
mln::image2d<mln::value::int_u8> working_img;
mln::image2d<mln::value::int_u8> *imLoad(const std::string path){
mln::io::pgm::load(working_img, path);
return &working_img;
}
void imSave(const std::string path){
mln::io::pgm::save(working_img, path);
}
What do you think about this?

How to get Python exception text

I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem.
If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.
How can i do it? I can't find any functions to get detailed exception information in Python API or Boost.
try {
module=import("MyModule"); //this line will throw excetion if MyModule contains an error
} catch ( error_already_set const & ) {
//Here i can said that i have error, but i cant determine what caused an error
std::cout << "error!" << std::endl;
}
PyErr_Print() just prints error text to stderr and clears error so it can't be solution
Well, I found out how to do it.
Without boost (only error message, because code to extract info from traceback is too heavy to post it here):
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
//pvalue contains error message
//ptraceback contains stack snapshot and many other information
//(see python traceback structure)
//Get error message
char *pStrErrorMessage = PyString_AsString(pvalue);
And BOOST version
try{
//some code that throws an error
}catch(error_already_set &){
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
handle<> hType(ptype);
object extype(hType);
handle<> hTraceback(ptraceback);
object traceback(hTraceback);
//Extract error message
string strErrorMessage = extract<string>(pvalue);
//Extract line number (top entry of call stack)
// if you want to extract another levels of call stack
// also process traceback.attr("tb_next") recurently
long lineno = extract<long> (traceback.attr("tb_lineno"));
string filename = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_filename"));
string funcname = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_name"));
... //cleanup here
This is the most robust method I've been able to come up so far:
try {
...
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
msg = handle_pyerror();
}
py_exception = true;
bp::handle_exception();
PyErr_Clear();
}
if (py_exception)
....
// decode a Python exception into a string
std::string handle_pyerror()
{
using namespace boost::python;
using namespace boost;
PyObject *exc,*val,*tb;
object formatted_list, formatted;
PyErr_Fetch(&exc,&val,&tb);
handle<> hexc(exc),hval(allow_null(val)),htb(allow_null(tb));
object traceback(import("traceback"));
if (!tb) {
object format_exception_only(traceback.attr("format_exception_only"));
formatted_list = format_exception_only(hexc,hval);
} else {
object format_exception(traceback.attr("format_exception"));
formatted_list = format_exception(hexc,hval,htb);
}
formatted = str("\n").join(formatted_list);
return extract<std::string>(formatted);
}
In the Python C API, PyObject_Str returns a new reference to a Python string object with the string form of the Python object you're passing as the argument -- just like str(o) in Python code. Note that the exception object does not have "information like line number" -- that's in the traceback object (you can use PyErr_Fetch to get both the exception object and the traceback object). Don't know what (if anything) Boost provides to make these specific C API functions easier to use, but, worst case, you could always resort to these functions as they are offered in the C API itself.
This thread has been very useful for me, but I had problems with the Python C API when I tried to extract the error message itself with no traceback. I found plenty of ways to do that in Python, but I couldn't find any way to do this in C++. I finally came up with the following version, which uses the C API as little as possible and instead relies much more on boost python.
PyErr_Print();
using namespace boost::python;
exec("import traceback, sys", mainNamespace_);
auto pyErr = eval("str(sys.last_value)", mainNamespace_);
auto pyStackTrace = eval("'\\n'.join(traceback.format_exception(sys.last_type, sys.last_value, sys.last_traceback))", mainNamespace_);
stackTraceString_ = extract<std::string>(pyStackTrace);
errorSummary_ = extract<std::string>(pyErr);
The reason this works is because PyErr_Print() also sets the value for sys.last_value, sys.last_type, and sys.last_traceback. Those are set to the same values as sys.exc_info would give, so this is functionally similar to the following python code:
import traceback
import sys
try:
raise RuntimeError("This is a test")
except:
err_type = sys.exc_info()[0]
value = sys.exc_info()[1]
tb = sys.exc_info()[2]
stack_trace = "\n".join(traceback.format_exception(err_type, value, tb))
error_summary = str(value)
print(stack_trace)
print(error_summary)
I hope someone finds this useful!
Here's some code based on some of the other answers and comments, nicely formatted with modern C++ and comments. Minimally tested but it seems to work.
#include <string>
#include <boost/python.hpp>
#include <Python.h>
// Return the current Python error and backtrace as a string, or throw
// an exception if there was none.
std::string python_error_string() {
using namespace boost::python;
PyObject* ptype = nullptr;
PyObject* pvalue = nullptr;
PyObject* ptraceback = nullptr;
// Fetch the exception information. If there was no error ptype will be set
// to null. The other two values might set to null anyway.
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
if (ptype == nullptr) {
throw std::runtime_error("A Python error was detected but when we called "
"PyErr_Fetch() it returned null indicating that "
"there was no error.");
}
// Sometimes pvalue is not an instance of ptype. This converts it. It's
// done lazily for performance reasons.
PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
if (ptraceback != nullptr) {
PyException_SetTraceback(pvalue, ptraceback);
}
// Get Boost handles to the Python objects so we get an easier API.
handle<> htype(ptype);
handle<> hvalue(allow_null(pvalue));
handle<> htraceback(allow_null(ptraceback));
// Import the `traceback` module and use it to format the exception.
object traceback = import("traceback");
object format_exception = traceback.attr("format_exception");
object formatted_list = format_exception(htype, hvalue, htraceback);
object formatted = str("\n").join(formatted_list);
return extract<std::string>(formatted);
}
Btw I was curious why everyone is using handle<> instead of handle. Apparently it disables template argument deduction. Not sure why you'd want that here but it isn't the same anyway, and the Boost docs say to use handle<> too so I guess there is a good reason.