python ctypes库3_如何传递并返回一个数组


可以将数组指针传递给dll,但无法返回数组指针,python中没有对应的数组指针类型。

如果需要返回数组,需借助结构体。

参考ctypes官方文档:

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

c++中

1、定义结构体

typedef struct StructPointerTest
{
char name[20];
int age;
int arr[3];
}StructPointerTest, *StructPointer;
2、定义函数

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM