-->

从C返回结构++ DLL到Python(Returning struct from c++ dll

2019-09-30 07:15发布

我试图返回结构,所以我可以在Python中使用它。 我初学编程的,所以请给我解释一下我在做什么错。 我已经成功地返回简单ctypes的早期(布尔,无符号整数),但结构是对我来说太复杂了。 这是我有:

DLLAPI.h

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

DLLAPI.cpp

EDIT1:不是TString,结构成员类型为wchar_t *现在,而是错误我得到的是相同的

...
typedef struct myStruct{
    wchar_t* id; 
    wchar_t* content; 
    wchar_t* message;
} myStruct;

DLLAPI myStruct* DLLApiGetStruct(){
    myStruct* test = new myStruct();
    test->id = _T("some id"); 
    test->content = _T("some content"); 
    test->message = _T("some message");
    return test;
}

这里是我的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

TString我用是的std :: wstring的

如果键入MYSTRUCT是指针或东西,而不是TString? 请帮我,我已经花5天尝试使这项工作。

Answer 1:

至于其他人解释,有问题的版本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;
}

蟒蛇

myDLL.DLLApiGetStruct.restype = POINTER(TestStruct)

显然,你必须只适用于这些变化的一个!

需要注意的是,在C ++代码,我选择使用显式宽串用L前缀,而不是_T()宏。 wchar_t的*后者,前者的比赛是你TCHAR使用什么。 我不会推荐TCHAR这些日子里,除非你需要支持Win98的。



Answer 2:

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

c_wchar_p包含wchar_t * ,不是std::wstring



Answer 3:

问题是,你正在返回包含结构std::string的,但你告诉Python中的类型是指向wchar_t的。 这与执行以下操作在C ++相同的效果。

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


文章来源: Returning struct from c++ dll to Python