python调用c的记录

官方给出的方法在这里点击打开链接

传入字符串的方法

char_p= c_wchar_p("hello word")
lib.python_write(str.encode(char_p.value) ,1111)
lib.python_write(b"hello",2222)
lib.python_write(str.encode("sdfsadfas"), 3333)
lib.python_write(bytes("dsfasdfas",encoding="utf-8"), 4444)

 

返回值的修改

默认返回c 的int类型如果需要修改使用restype

#测试调用的返回类型
lib.python_write.restype = c_int        #可以指定为ctypes中允许的类型
result = lib.python_write(bytes("中文", encoding="utf-8"), 55555)
print(result)


 
通过指针修改值,实现数据的返回
    i= c_int(1)     #申请一个c的int形指针,并将初始值设置为1
    f= c_double(3.1415)
    s= create_string_buffer(b'\000yuan', 32)
    lib.python_read(str.encode("通过指针返回值"), byref(i))        #通过byref()方法将指针传递下去,并在C中实现修改指针对应的值,注意字符串比较特殊
    print(i.value)
结构体和共用体的传递
    print("结构体测试")
    class POINT(Structure):     #继承Structure类
        _fields_ = [("x", c_int), ("y", c_double)]      #必须使用_fields_这种固定的格式

    point= POINT(10, 20.121)    # 实例化一个结构体类,可以支持空参数初始化
    print(point.x , point.y)
    point= POINT(y=6.6)
    print(point.x, point.y)
    point1= POINT(x=1,y=2.2)
    #结构体中又包括结构体
    class RECT(Structure):
        _fields_ = [("upperleft", POINT), ("lowerright", POINT)]

    rc=RECT(point, point1)
    print(rc.upperleft.x, rc.upperleft.y)
    print(rc.lowerright.x, rc.lowerright.y)
    rc1= RECT(POINT(1,1.1), POINT(2,2.2))           #可以支持    rc1= RECT((3, 3.3), (4, 4.4))这种方式
    print(POINT.x, POINT.y)



数组的操作
 print("数组的操作\n")
    TenPointsArrayType= POINT *10           #申请了10元素的一个数组
    #
    class MyStructure(Structure):           # 在这个结构体中包括了4个point类型的指针
        _fields_ = [("a", c_int), ("b", c_double), ("c", c_int, 16), ("point_array", POINT*11)]      #POINT*11变成了一个数组

    mystr1 = MyStructure()
    arr=TenPointsArrayType()
    mystr1.point_array[1]= (1, 1.1)
    for pt in mystr1.point_array:
        print(pt.x,pt.y)

    # TenIntegers = c_int * 10
    # ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    # for i in ii:
    #     print(i, end=" ")

    TenIntegers = POINT * 10
    ii = TenIntegers((1,1.1),(2, 2.2))      #不能写为list必须都是原组

    for i in ii:
        print(i.x, i.y , end=" ")


单独使用指针的功能
    i= c_int(22)
    pi= pointer(i)              #使用POINTER()可以不用指定类型,少pointer()一些操作
    pi.contents.value=33
    print(pi.contents, pi.contents.value)
    #检查指针是不是空的POINTER(c_int)是一个野指针
    null_ptr = POINTER(c_int)()     #POINTER(c_int)() 等价于null_ptr = POINTER(c_int)  null_ptr= ()
    print(bool(null_ptr))           #这里的就是一个空指针



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值