python调用c/c++动态库,并在回去回调函数中的void*指向的值

说明

最近几天在做一个小模块,使用python调用第三方提供的c/c++动态库,主要难点是回调函数的使用和如何在自己定义的回调函数中获取void *等类型的值

使用c编写动态库

c语言动态库代码

mycallback.c

#include <stdio.h>
#include <stdlib.h>
#include <string>

//g++ -std=c++11 mycallback.c -shared -fPIC -o libcallback.so

typedef struct Student{
    int age;
    char name[10];
}Student;

extern "C" int Receive(char *path,void *callback(char *fullname,void *void_char,void *void_int,void *void_struct),void *context)
{
    /*char *void_char = (char*)malloc(10);
    void_char = "中国";
    int *void_int = (int*)malloc(sizeof(int));
    *void_int = 98789;*/
    char *void_char = "中国";
    int void_int = 1001;
    printf("void_char=%s\n",void_char);
    printf("void_int=%d\n",void_int);

    Student stu;
    stu.age= 100;
    strcpy(stu.name,"张三");

    printf("将文件存储到了%s目录下\n",path);
    printf("开始调用回调函数\n");
    callback("/user/local/test.txt",(void*)(void_char),(void*)(&void_int),(void*)(&stu));
    printf("调用回调函数结束\n");


    return 0;
}

编译

g++ -std=c++11 mycallback.c -shared -fPIC -o libcallback.so

编写python代码

mycallback.py

from ctypes import *

INTARRAY8 = c_int * 8



'''
typedef struct Student
{
    int     age;
    char *  name;
    void *  ptr;
    int     score[8];
}Student;
'''

class Student(Structure):

    _fields_ = [
        ("age", c_int),
        ("name", c_char*10),
    ]


solib = cdll.LoadLibrary("./libcallback.so")

# 设置调用函数的信息
# int Receive(char *path,void *callback(char *fullname,void *handle),void *context)
solib.Receive.restype=c_int
solib.Receive.argtypes=[c_char_p,CFUNCTYPE(c_void_p,c_char_p,c_void_p,c_void_p,POINTER(Student)),c_void_p]# CFUNCTION第一个参数是返回值类型,后面的是参数类型

# 初始化传入函数的阐述
path = "/usr/local/lib"

def callback(fullname,viod_char,void_int,void_struct):
    print(fullname)
	# 将void *类型的指针转换为char *,并获取其指向的值
    print(cast(viod_char, c_char_p).value.decode())
    # 将void *类型的指针转换为int *,并获取其指向的值
    print(cast(void_int, POINTER(c_int)).contents.value)
    # 将void *类型的指针转换为Student *,并获取其指向的值
    stu = cast(void_struct, POINTER(Student)).contents
    print(stu.name)
    print(stu.age)

func_type = CFUNCTYPE(c_void_p, c_char_p,c_void_p,c_void_p,POINTER(Student))
context = cast(pointer(c_int(1000)),c_void_p)

# 调用c中的Receive函数
solib.Receive(path.encode(),func_type(callback),context)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值