Ctypes返回值和参数的地址截断

在ARM平台上,python脚本使用ctypes方法调用C动态库,C动态库中void*类型的值返回到python中,地址被截断。代码如下:

// the interface of C library
// c.h

#ifdef __cplusplus
extern "C" {
#endif

#define _stdcall

void *_stdcall GetVoidPoint();

int _stdcall TestVoidPoint(void* pvPoint);

#ifdef __cplusplus
}
#endif
// the interface of C library
//c.cpp

#include <stdio.h>
#include <unistd.h>
#include "c.h"

class CMyClass
{
public:
	CMyClass()
	{
		num1 = 5;
	}

	void PrintInfo()
	{
		printf("in dll, num1 = %d\n", num1);
	}
private:
	int num1;
};

void* _stdcall GetVoidPoint()
{
	CMyClass *pMyClass = new CMyClass();
	printf("in dll, GetVoidPoint, pMyClass = %p\n", pMyClass);
	return pMyClass;
}

int _stdcall TestVoidPoint(void* pv)
{
	printf("in dll, TestVoidPoint, pvPoint = %p\n", pv);
	CMyClass *pTmp = (CMyClass*)pv;
	pTmp->PrintInfo();
	delete pTmp;
	return 0;
}
#_*_ coding:cp936 _*_
from ctypes import *
import string


if __name__=="__main__":
    test_Handle = cdll.LoadLibrary(r"libtest_c.so")
    
    #set return type
    #test_Handle.GetVoidPoint.restype = c_void_p
    ret1 = test_Handle.GetVoidPoint()
    print "ret1 = %#x" %(ret1)

    #set argument type
    #test_Handle.TestVoidPoint.argtypes = [c_void_p]
    ret2 = test_Handle.TestVoidPoint(ret1)
    print "ret2 = %d" %ret2

​

在ARM平台下,不设置返回值和参数类型,那么结果如下:
​​​​​​未使用restype和argtypes
在ARM平台下,设置返回值和参数类型,那么结果如下:

使用restype和argtypes
原因分析:

​(1)默认情况下,ctype的返回值的类型是int。python中int类型对应C中的int类型,c中int类型在64位机器上的是4个字节,占32位。ARM平台下,获取到的地址是12位16进制,总共48位,例如:0xaaadf0f0caca(其实是0x0000aaadf0f0caca,高四位用不到),如果python没有设置返回值是c_void_p,那么在void*转int类型时,返回值的位数被截断为32位,例如:0xf0f0caca。

(2)默认情况下,ctype的参数的类型是int。此时以0xf0f0caca的值传入C动态库,在动态库中的地址其实表示的0xfffffffff0f0caca,和之前获取到的地址0x0000aaadf0f0caca就不是一个地址了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值