【求助】使用C++调用Python函数,传递中文字符串失败。

diskingchuan 2011-07-04 05:20:08
Python Version : 3.1.2

...
std::string string1 = "u\"你好\"";
pArgs = Py_BuildValue("(s)",string1.c_str());
pFunc = PyObject_GetAttrString(pModule, "Test1");
...

pArgs = Py_BuildValue() 返回是空,但是如果传递string1 = "111","ddd"之类的字符肯定是没有问题。

总结如下:"你好" 失败 "u\"你好\""失败 "ddd" 成功

求各位大神,帮忙看一下是哪里出的问题~~~~~
...全文
494 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
diskingchuan 2011-07-05
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 iambic 的回复:]
另外按照文档,如果Py_BuildValue返回NULL,可以检查下PyExc_SystemError。
[/Quote]

搞定了,不过比较土,只能说我在VS的开发环境中,转换成Unicode编码,然后做为参数传到Python函数中,

Python3的默认Unicode很头疼啊。
iambic 2011-07-04
  • 打赏
  • 举报
回复
另外按照文档,如果Py_BuildValue返回NULL,可以检查下PyExc_SystemError。
iambic 2011-07-04
  • 打赏
  • 举报
回复
测试通过:

#include <Python.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
Py_Initialize();
//PyObject* pArgs = Py_BuildValue("(s)", "中文");
PyObject* pArgs = Py_BuildValue("(s)", "\xe4\xbd\xa0\xe5\xa5\xbd");
printf("%p\n", pArgs);
printf("%s\n", PyString_AsString(PyObject_Str(pArgs)));
Py_Finalize();
return 0;
}


输出:
02496050
('\xe4\xb8\xad\xe6\x96\x87',)


如果你有问题,请像我一样贴段能独立编译通过的最短的代码来说明你的问题。



diskingchuan 2011-07-04
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 iambic 的回复:]
你把"中文"改成"\xe4\xbd\xa0\xe5\xa5\xbd"试下。我刚下了个Python,有空的话也试下。
[/Quote]

是这样的,我传入的是大量的中文字符串,

Python难道现在还不能直接传入中文字符吗?
iambic 2011-07-04
  • 打赏
  • 举报
回复
你把"中文"改成"\xe4\xbd\xa0\xe5\xa5\xbd"试下。我刚下了个Python,有空的话也试下。
diskingchuan 2011-07-04
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 iambic 的回复:]
源文件编码是什么?
[/Quote]

coding:utf-8 ,编码这么长时间,第一次遇到这个问题,
iambic 2011-07-04
  • 打赏
  • 举报
回复
源文件编码是什么?
huaxinwu 2011-07-04
  • 打赏
  • 举报
回复
是个TCL的例子
huaxinwu 2011-07-04
  • 打赏
  • 举报
回复
CString Utf2Str(Tcl_Interp *interp, const char *utf)
{
if (utf == NULL)
{
return "";
}
CString str;

Tcl_Encoding encoding = Tcl_GetEncoding(interp, NULL);

Tcl_DString ds;
char *pData = Tcl_UtfToExternalDString(encoding, utf, strlen(utf), &ds);

str = pData;

Tcl_DStringFree(&ds);
Tcl_FreeEncoding(encoding);

return str;
}

CString Str2Utf(Tcl_Interp *interp, const char *str)
{
CString utf;

Tcl_Encoding encoding = Tcl_GetEncoding(interp, NULL);

Tcl_DString ds;
char *pData = Tcl_ExternalToUtfDString(encoding, str, strlen(str), &ds);

utf = pData;

Tcl_DStringFree(&ds);
Tcl_FreeEncoding(encoding);

return utf;
}
huaxinwu 2011-07-04
  • 打赏
  • 举报
回复
把字符串转成 UTF格式试试……

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧