Python调用C动态库并通过bytes传参

发布时间 2023-11-09 09:43:44作者: 立秋了

通过Python内建库ctypes调用C语言。

#!/usr/bin/python3

# file : bytes_test.py

import ctypes as ct
import os

# 编译C程序为动态库
os.system("gcc -fpic -shared bytes_test.c -o bytes_test.dll")

# 加载动态库
clib = ct.CDLL("./bytes_test.dll")

# 分配内存
src = b"0123"
out = bytes(len(src))

print(f"src={src}, out={out}")

# 取指针
src_ptr = ct.cast(src, ct.c_char_p)
out_ptr = ct.cast(out, ct.c_char_p)

# 调用C函数
clib.copy(out_ptr, src_ptr, len(src))

print(f"src={src}, out={out}")

// file : bytes_test.c

int copy(unsigned char *out, unsigned char *src, int size)
{
	int i;
	
	for(i=0; i<size; ++i){
		out[i] = src[i];
	}
	return i;
}