我正在使用 msvc++ 和 Python 2.7。我有一个返回 std:wstring 的 dll。我试图以这样一种方式包装它,即它作为 c 样式字符串公开,以便通过 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;
}
python :
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 程序员,但字符数据通常在两种不同语言之间编码的方式是将字符复制到在接收方或发送方创建的缓冲区(前者比后者更好)。
关于Python ctypes 和包装 c++ std :wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25515646/