[英]Using Unicode in Boost Python with a C++ function that takes std::wstring
[英]Python ctypes and wrapping a c++ std:wstring
我正在使用msvc ++和Python 2.7。 我有一个返回std:wstring的dll。 我试图将其包装为通过ctypes从Python调用的交流样式字符串。 我显然对这两者之间的字符串处理方式一无所知。 我已将其简化为一个简单的示例,以了解传递机制。 这是我所拥有的:
C ++
#include <iostream>
class WideStringClass{
public:
const wchar_t * testString;
};
extern "C" __declspec(dllexport) WideStringClass* WideStringTest()
{
std::wstring testString = L"testString";
WideStringClass* f = new WideStringClass();
f->testString = testString.c_str();
return f;
}
蟒蛇:
from ctypes import *
lib = cdll.LoadLibrary('./myTest.dll')
class WideStringTestResult(Structure):
_fields_ = [ ("testString", c_wchar_p)]
lib.WideStringTest.restype = POINTER(WideStringTestResult)
wst = lib.WideStringTest()
print wst.contents.testString
并且,输出:
????????????????????᐀㻔
我想念什么?
编辑:将C ++更改为以下即可解决该问题。 当然,我想我现在有内存泄漏。 但是,可以解决。
#include <iostream>
class WideStringClass{
public:
std::wstring testString;
void setTestString()
{
this->testString = L"testString";
}
};
class Wide_t_StringClass{
public:
const wchar_t * testString;
};
extern "C" __declspec(dllexport) Wide_t_StringClass* WideStringTest()
{
Wide_t_StringClass* wtsc = new Wide_t_StringClass();
WideStringClass* wsc = new WideStringClass();
wsc->setTestString();
wtsc->testString = wsc->testString.c_str();
return wtsc;
}
谢谢。
有一个与Python无关的大问题:
f->testString = testString.c_str();
这是不正确的,因为testString
(您声明的std::wstring
)是一个局部变量,并且一旦该函数返回, testString
就消失了,从而使使用c_str()
返回值的任何尝试均无效。
那么如何解决这个问题? 我不是Python程序员,但是字符数据通常在两种不同语言之间进行编组的方式是将字符复制到在接收方或发送方(最好是前者比后者)创建的缓冲区中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.