0

I develop an application in C++ with WWW interface in Django. So far I have working framework in C++ with Boost.Python wrapper compiled to shared object in Linux.

Now I try to run this framework in Django. When I pass string from form "CharField" I get this error:

Python argument types in
CoreSystem.setOutput(CoreSystem, unicode)
did not match C++ signature:
setOutput(CoreSystem {lvalue}, std::string)

Code responsible for that is here:

form = AnalyzeForm(request.POST)
if form.is_valid():
    cd = form.cleaned_data
    s.setOutput(cd["output"])

where s is this CoreSystem object. If I type it like this:

s.setOutput("DatabaseOutput")

it works fine. I used also str(cd["output"]) but after that nothing happens.

I'm using Django 1.4.1 and Python 2.7.3

eclipse
  • 693
  • 9
  • 30

1 Answers1

2

You can use the encode method to convert a Unicode string to a byte string before sending it off to the C++ code that expects a string:

s.setOutput(cd["output"].encode("utf-8"))

The UTF-8 encoding is a reasonable default for Unicode strings. If cd["output"] is already an ASCII string, encoding will not change it; if it contains binary data, you will get an exception.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • Unfortunately when I do this, nothing happens but with no error. I put even printf in setOutput and it doesn't print anything. Just as if setOutput wasn't called at all. – eclipse Sep 10 '12 at 21:58
  • Your answer did the trick. Previous error was due to bad server configuration. – eclipse Sep 10 '12 at 22:12
  • Another interesting thing to try would be to overload the function to accept a `std::wstring`. If Boost.Python is smart enough to generate a wrapper that automatically converts `str` to `std::string`, it might do the same for conversion of `unicode` to `std::wstring`. – user4815162342 Sep 10 '12 at 22:41
  • but then how do you convert to wstring to string? –  Mar 21 '14 at 23:46
  • @RodrigoSalazar In that case one would need to implement encoding from wide-character to multibyte using C++ facilities. The accepted answer to [This SO question](http://stackoverflow.com/questions/4804298/how-to-convert-wstring-into-string) shows an approach that should be portable. [This answer](http://stackoverflow.com/a/18374698/1600898) to the same question offers an easier C++11 solution. – user4815162342 Mar 22 '14 at 07:16