简体   繁体   English

如何将Django unicode转换为C ++ std :: string

[英]How to convert in Django unicode to C++ std::string

I develop an application in C++ with WWW interface in Django. 我在Django中使用WWW接口在C ++中开发了一个应用程序。 So far I have working framework in C++ with Boost.Python wrapper compiled to shared object in Linux. 到目前为止,我在C ++中使用Boost.Python包装器编译到Linux中的共享对象。

Now I try to run this framework in Django. 现在我尝试在Django中运行这个框架。 When I pass string from form "CharField" I get this error: 当我从表单“CharField”传递字符串时,我收到此错误:

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. 其中s是此CoreSystem对象。 If I type it like this: 如果我这样输入:

s.setOutput("DatabaseOutput")

it works fine. 它工作正常。 I used also str(cd["output"]) but after that nothing happens. 我也使用了str(cd [“output”])但之后没有任何反应。

I'm using Django 1.4.1 and Python 2.7.3 我正在使用Django 1.4.1和Python 2.7.3

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: 您可以使用encode方法将Unicode字符串转换为字节字符串,然后将其发送到需要字符串的C ++代码:

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

The UTF-8 encoding is a reasonable default for Unicode strings. UTF-8编码是Unicode字符串的合理默认值。 If cd["output"] is already an ASCII string, encoding will not change it; 如果cd["output"]已经是ASCII字符串,则编码不会改变它; if it contains binary data, you will get an exception. 如果它包含二进制数据,您将获得异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM