通过pypdfium2-team/ctypesgen 快速生成ctypes 代码

以前说过ctypesgen 的作用,以下是一个简单试用

项目准备

  • 代码结构
├── add.c
├── add.h
├── add.so
├── app.py
├── common.h
├── init_patch.py
├── pyadd.py
└── README.md
  • 代码说明 add.h 是方法定义,add.c 是实现,pyadd.py 是通过ctypesgen 生成的代码,app.py是调用 add.h
#ifndef ADD_H
#define ADD_H
#include "common.h"

int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
User init_user(int id, const char *name);
#endif

common.h

#ifndef COMMON_H
#define COMMON_H

typedef struct {
    int id;
    const char *name;
} User;

#endif // COMMON_H

add.c

#include "add.h"

int add(int a, int b) {
    return a + b;
}

User init_user(int id, const char *name) {
    User user;
    user.id = id;
    user.name = name;
    return user;
}

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}
int divide(int a, int b) {
    if (b == 0) {
        // Handle division by zero error
        return 0; // or some error code
    }
    return a / b;
}
  • 构建共享库
gcc -fPIC -shared add.c -o add.so

生成ctypes 代码

ctypesgen -i add.h -l add -L './add.so' -o pyadd.py
  • python 调用 app.py
rom pyadd import init_user,add,subtract,multiply,divide

from ctypes import create_string_buffer,string_at

name_buffer = create_string_buffer(b"dalong")
result = init_user(1, b"dalong")

print("The result of init_user(1, 'dalong') is:", result.id, string_at(result.name))

result = add(1, 2)
print("The result of add(1, 2) is:", result)

result = subtract(5, 3)
print("The result of subtract(5, 3) is:", result)

result = multiply(4, 3)
print("The result of multiply(4, 3) is:", result)

result = divide(10, 2)
print("The result of divide(10, 2) is:", result)
  • 效果

image

说明

通过pypdfium2-team/ctypesgen 生成ctypes 调用代码还是很不错的,机制上比较符合我们平时的访问,就是目前默认生成方法中的_get_library 似乎不是很友好(默认实现比较中规中矩,很多时候我们对于lib的调用会有清晰的dir 命名,同时打包在一起,方便使用)目前这部分似乎不能自定义(还得研究下)

参考资料

https://github.com/pypdfium2-team/ctypesgen

https://github.com/rongfengliang/ctypesgen-learning

posted on 2025-10-16 08:00  荣锋亮  阅读(5)  评论(0)    收藏  举报

导航