python ctypes庫3_如何傳遞並返回一個數組

能夠將數組指針傳遞給dll,但沒法返回數組指針,python中沒有對應的數組指針類型。html

若是須要返回數組,需藉助結構體。python

參考ctypes官方文檔:c++

https://docs.python.org/3.6/library/ctypes.html#structures-and-unions數組

 

返回一個結構體例程:函數

# 返回結構體
import ctypes
path = r'E:\01_Lab\VisualStudioLab\cpp_dll\cpp_dll\Debug\cpp_dll.dll'
dll = ctypes.WinDLL(path)

class StructPointer(ctypes.Structure):
_fields_ = [("name", ctypes.c_char * 20),
("age", ctypes.c_int),
("arr", ctypes.c_int * 3)]

dll.test.restype = ctypes.POINTER(StructPointer)
p = dll.test()

print(p.contents.name)
print(p.contents.age)
print(p.contents.arr[0])
print(p.contents.arr[1])
print(p.contents.arr[2])spa

c++中指針

一、定義結構體rest

typedef struct StructPointerTest
{
char name[20];
int age;
int arr[3];
}StructPointerTest, *StructPointer;
二、定義函數htm

DLLEXPORT StructPointer __stdcall test() // 返回結構體指針
{
StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));
strcpy(p->name, "Joe");
p->age = 20;
p->arr[0] = 3;
p->arr[1] = 5;
p->arr[2] = 10;

return p;
} 文檔

相關文章
相關標籤/搜索