0
点赞
收藏
分享

微信扫一扫

Python&C++相互混合调用编程全面实战-08ctypes获取函数的返回值


作者:虚坏叔叔

早餐店不会开到晚上,想吃的人早就来了!😄

ctypes获取函数的返回值

如何通过​​ctypes​​​获取​​c语言​​的返回值。首先需要考虑的是返回值的内存的空间在哪边。加入返回的是指针 需要考虑到指针的空间在哪边释放,这算是一个比较危险的操作,假定你在c中申请了空间,在Python中就没有办法释放,就会出现问题,

返回值之前我们都是用​​void​​​,如果你没设置返回值,默认的就都是​​int​​。

可以通过如下代码制定返回类型:

lib.CFuntion.restype = c_char_p

一、实战

c++中定义好了3个函数,

XLIB int TestReturnInt()
{
return 101;
}

XLIB char* TestReturnChar()
{
return "TestReturnCHar String";
}

XLIB wchar_t* TestReturnWChar()
{
return L"TestReturnWCHar String";
}

Python&C++相互混合调用编程全面实战-08ctypes获取函数的返回值_qt

来到Python代码当中,

print("Test Ctypes")
from ctypes import *

#导入库 windows中dll后缀名不用加
lib = CDLL("C:\\Users\\Administrator\\Desktop\\testctypes\\x64\\Debug\\testctypes")

try:
print("TestReturnInt=", lib.TestReturnInt())
lib.TestReturnChar.restype = c_char_p
print("TestReturnChar=", lib.TestReturnChar())
lib.TestReturnWChar.restype = c_wchar_p
print("TestReturnWChar=", lib.TestReturnWChar())
except Exception as ex:
print("testCtypes Error", ex)
# 等待用户输入,程序不退出
input()

运行结果如图

Python&C++相互混合调用编程全面实战-08ctypes获取函数的返回值_qt_02

二、总结

  • 本文使用Qctypes获取函数的返回值 。

举报

相关推荐

0 条评论