将struct从c++dll返回到Python

2024-10-02 18:14:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以在Python结构中使用它。我做错了什么程序员请解释一下。我已经成功地返回了简单的ctypes(bool,unsigned int),但是struct对我来说太复杂了。这就是我所拥有的:

德拉皮

#define DLLAPI extern "C" __declspec(dllexport)
...
DLLAPI myStruct* DLLApiGetStruct();

在德拉皮.cpp在

EDIT1:struct members type不是TString,而是wchar\u t*,但我得到的错误是相同的

^{pr2}$

下面是我的Python代码:

...
class TestStruct(Structure):
    _fields_ = [
        ("id", c_wchar_p),
        ("content", c_wchar_p),
        ("message", c_wchar_p)
        ]
class SomeClass(object):
    ....  
    def test(self):
        myDLL = cdll.LoadLibrary('myDLL.dll')
        myDLL.DLLApiGetStruct.restype = TestStruct
        result = myDLL.DLLApiGetStruct()
        print "result type: ", type(result)
        print "-"*30
        print "result: ",result
        print "-"*30
        print result.id # line 152

我得到的是:

    result type:  <class 'Foo.TestStruct'>
    ------------------------------
    result:  <Foo.TestStruct object at 0x027E1210>
    ------------------------------
    Traceback (most recent call last):
    ....
    ....
    ....
    line 152, in test
        print result.id
    ValueError: invalid string pointer 0x00000002

我使用的字符串是std::wstring

myStruct中的类型应该是指针还是其他什么,而不是TString? 请帮帮我,我已经花了5天的时间来做这个。在


Tags: testidobjecttyperesultstructclassprint
3条回答

正如其他人所解释的,问题的版本1的问题是使用std::string,这不是一个有效的互操作类型。在

查看问题的第2版,C++和Python声明不匹配。C++代码返回指向结构的指针,但是Python代码期望结构由值返回。在

可以更改C++或Python以匹配其他。在

<强> C++ >强>

DLLAPI myStruct DLLApiGetStruct()
{
    myStruct result;
    result.id = L"some id";
    result.content = L"some content";
    result.message = L"some message";  
    return result;
}

Python

^{pr2}$

显然,您必须只应用这些更改中的一个!在

注意,在C++代码中,我选择使用L前缀而不是γ()宏使用显式宽字符串。前者与wchar_t*匹配,后者与TCHAR一起使用。我现在不推荐TCHAR,除非你需要支持Win98。在

问题是,你正在返回一个包含^ {CD1>}的结构,但是你在告诉Python,这些类型是指向WC++的指针。在

struct Foo
{
    std::string id; 
    std::string content; 
    std::string message;
};

struct Bar
{
    wchar_t* id; 
    wchar_t* content; 
    wchar_t* message;
};

Foo f;
Bar* = reinterpret_cast<Bar*>(&f);

http://docs.python.org/3.1/library/ctypes.html

c_wchar_p包含wchar_t *,而不是{}

相关问题 更多 >