Python ctypes returned c_char_p is corrupted

  c++, character-encoding, ctypes, python, string

I have a C++ interface that contains the following:

extern "C"
{
     char const* getValForEntry(Entry e)
     {
         std::string no_val = "__err::no_val";
         if (handles.find(e) != handles.end())
         {
             std::string val = handles[e]->get_value();
             return val.c_str();
         }
         else
             return no_entry.c_str();
     }
}

I have a python app that connects to this interface with ctypes like so:

self.lib.getUpdateForEntry.restype = c_char_p
val = self.lib.getUpdateForEntry(e)

The interface returns the string:

{"RVC HR1":{"Mode":1,"Seq Num":162,"Home":7,"Time":"Thu Sep 01 10:00:00 2000","Flags":0,"Data Len":1024,"Data":[26, ... an array of 1024 values ... ,239]}}

What the python app is seeing is:

p??"Mode":1,"Seq Num":162,"Home":7,"Time":"Thu Sep 01 10:00:00 2000","Flags":0,"Data Len":1024,"Data":[26, ... an array of 1024 values ... ,239]}}

The message is suppsosed to be a string with 2844 chars in it, but in python, the first 12 chars are always corrupted, and I see the message:

'utf8' codec can't decode byte 0xb1 in position 1: invalid start byte

If I adjust the message to only have a handful of values in the array (under 10) then the message is fine, but when I add more values, the first part of the message gets corrupted. Does anyone know why I am seeing this? Is there a max c_char_p length, or is it being returned as ascii and converted to unicode? Is it something else?

Source: Windows Questions C++

LEAVE A COMMENT