Reputation: 4029
I am using msvc++ and Python 2.7. I have a dll that returns a std:wstring. I am trying to wrap it in such a way that it is exposed as a c style string for calls from Python via ctypes. I obviously do not understand something about how strings are handled between the two. I have simplified this into a simple example to understand the passing mechanism. Here is what I have:
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
And, the output:
????????????????????᐀㻔
What am I missing?
Edit: Changing the C++ to the following solves the problem. Of course, I think I now have a memory leak. But, that can be solved.
#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;
}
Thanks.
Upvotes: 1
Views: 715
Reputation: 35440
There is a big issue that is not related to Python:
f->testString = testString.c_str();
This is not correct, since testString
(the std::wstring
you declared) is a local variable, and as soon as that function returns, testString
is gone, thus invalidates any attempt to use what c_str()
returned.
So how do you fix this? I'm not a Python programmer, but the way character data is usually marshalled between two differing languages is to copy characters to a buffer that was either created on the receiver's side or the sender's side (better the former than the latter).
Upvotes: 1