Python ctypes 和包装 c++ std :wstring

标签 python c++ ctypes

我正在使用 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/

相关文章:

c++ - Git:C++ 格式不可知注释

Python:Ctypes如何检查内存管理

python - 检索集合的输入。计数器输出

python - open() 中的整数文件描述符 "0"

python - (Python)为什么不在函数中导入模块而不是在开头导入它们的最佳方式?

Python ctypes 回调函数给出 "TypeError: invalid result type for callback function"

python - 是否有在 cygwin 上安装 Kivy 的说明?

Python 3 错误 - TypeError : input expected at most 1 arguments, 得到 3

c++ - 使用批处理文件和 C++ 的环境变量

c++ - 构建基于状态的游戏引擎和 Makefile 结构有帮助吗?