c++ - 将结构从 C++ dll 返回到 Python

标签 c++ python struct ctypes dllexport

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

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 天时间来完成这项工作。

最佳答案

正如其他人所解释的那样,问题版本 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

myDLL.DLLApiGetStruct.restype = POINTER(TestStruct)

显然,您必须只应用其中一项更改!

请注意,在 C++ 代码中,我选择使用带有 L 前缀的显式宽字符串而不是 _T() 宏。前者与 wchar_t* 匹配,后者是您与 TCHAR 一起使用的内容。这些天我不会推荐 TCHAR,除非你需要支持 Win98。

关于c++ - 将结构从 C++ dll 返回到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20773602/

相关文章:

C++ 在全局命名空间中找不到非标准 C 函数

python - 如何设置 keras 自定义指标仅在纪元结束时调用?

python - 如何使用包 url 来 pip 列表

python - 类和变量

c++ - 将语言环境更改为瑞典语

c++ - 为 iPhone 设备编译但不为模拟器编译的代码

c++ - c++ - 如何在运行时在c++中停止程序3秒

c - 使用 {0} 或 {'\0' } 初始化结构之间有什么区别吗?

c# - 为什么编译器为 "yield"生成的枚举器不是结构?

c - 错误 : expected specifier qualifier list before FILE in header struct