将结构从 c++ dll 返回到 Python
Returning struct from c++ dll to Python
我正在尝试返回结构,以便我可以在Python中使用它。我是初学者程序员,所以请解释我做错了什么。我之前已经成功地返回了简单的 ctypes(bool,无符号 int),但结构对我来说太复杂了。这是我所拥有的:
DLLAPI.h
#define DLLAPI extern "C" __declspec(dllexport)
...
DLLAPI myStruct* DLLApiGetStruct();
DLLAPI.cpp
EDIT1:结构成员类型现在不是 Ttring,而是 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
我用过的是std::wstring
输入 myStruct 应该是指针还是其他东西?请帮助我,我已经花了 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;
}
蟒
myDLL.DLLApiGetStruct.restype = POINTER(TestStruct)
显然,您只能应用这些更改之一!
请注意,在C++代码中,我选择使用带有 L 前缀的显式宽字符串,而不是 _T() 宏。前者与 wchar_t* 匹配,后者是 TCHAR 使用的。这些天我不推荐 TCHAR,除非你需要支持 Win98。
> http://docs.python.org/3.1/library/ctypes.html
c_wchar_p
包含wchar_t *
,而不是std::wstring
问题是你返回了一个包含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);
- 从python中调用C++函数并获取返回值
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- C++返回 Numpy 数组的 Python 扩展模块
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针
- 使用 Main() 返回值作为 python 脚本的参数
- std::endl,在 Python 中是否有等价物?(返回 + 刷新)
- C++ python 中的函数返回数字而不是字符串
- Python os.system() 返回错误值
- 从 C++ 函数与 Python 函数返回的不一致值用于偏斜正态分布
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 更改 Python 切换的 C 函数的返回值类型
- C++ & Python:传递并返回从 python 到 c++ 的 2D 双指针数组
- 如何将 Python 对象转换为 Cython 扩展类型的 std::vector 并返回?
- 如何将 cv::mat 对象从 python 模块传递到 c++ 函数并返回返回的 cv::mat 类型为对象?
- 如何让 SWIG 返回 Python 2 中字符串的 unicode 对象
- 从动态库交互式调用函数,无需等待返回(python,ctypes)
- 引用从 Python 传递到 Boost::p ython 并返回 Python
- 如何从C++返回 Python 类型的实例
- 返回python中的c++对象(最好不是指针)