我使用的是msvc++和python2.7。我有一个dll,它返回标准:wstring。我试图将它包装成一个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:
^{pr2}$输出:
????????????????????᐀㻔
我错过了什么?在
编辑: 将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程序员,但是字符数据在两种不同语言之间进行编组的方式通常是将字符复制到在接收方或发送方创建的缓冲区(前者比后者更好)。
相关问题 更多 >
编程相关推荐