[英]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.