简体   繁体   中英

Python ctypes and wrapping a c++ std:wstring

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 ac 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM