python - 如何使用 ctypes 将 byteArray 传递给以 char* 作为参数的 C 函数?

标签 python c shared-libraries ctypes

我在 C 中创建了一个函数,它接受一个 int 大小和一个 char *buffer 作为参数。我想使用 ctypes 从 python 调用此函数并传入 python byteArray。我知道首先你必须将 C 文件编译成一个共享库(.so 文件)并使用 ctypes 来调用该函数。这是我到目前为止的代码。

加密.c:

#include <stdio.h>
void encrypt(int size, unsigned char *buffer);
void decrypt(int size, unsigned char *buffer);

void encrypt(int size, unsigned char *buffer){
    for(int i=0; i<size; i++){
        unsigned char c = buffer[i];
        printf("%c",c);
    }
}
void decrypt(int size, unsigned char *buffer){
    for(int i=0; i<size; i++){
        unsigned char c = buffer[i];
        printf("%c",c);
    }
}

这是 python 文件:

import ctypes

encryptPy = ctypes.CDLL('/home/aradhak/Documents/libencrypt.so')
hello = "hello"
byteHello = bytearray(hello)
encryptPy.encrypt(5,byteHello)
encryptPy.decrypt(5,byteHello)

基本上我想从 python 调用 C 方法,传递一个 python 字节数组,并让它遍历数组并打印每个元素

最佳答案

Mark 的回答非常有帮助,因为它将字符数组传递给 C 函数,这是 OP 真正想要的,但如果有人在这里找到他们真正想要传递字节数组的方式,an approach seems to be to build a ctypes.c_char backed by the memory of your byte-array, and pass that .

我这里的例子忽略了 Mark 推荐的参数声明,这看起来确实是个好主意。

import ctypes

# libFoo.c:
# (don't forget to use extern "C" if this is a .cpp file)
#
# void foo(unsigned char* buf, size_t bufSize) {
#   for (size_t n = 0; n < bufSize; ++n) {
#     buf[n] = n;
#   }
# }

fooLib = ctypes.cdll.LoadLibrary('./lib/libFoo.dylib')

ba = bytearray(10)

char_array = ctypes.c_char * len(ba)

fooLib.foo(char_array.from_buffer(ba), len(ba))

for b in ba:
  print b

# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

关于python - 如何使用 ctypes 将 byteArray 传递给以 char* 作为参数的 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37422662/

相关文章:

c - ELF中全局变量的顺序

c - "undefined reference to"用于共享库中的符号

python - 使用 pandas 数据框进行主成分分析

Python AWS BOTO 错误

python - 为什么 os.system ('cls' ) 不清除最近的输出?

c - 整数除法 (1/n) 的结果始终向下舍入为 0.000

在多列上运行的 Python pandas groupby 转换/应用函数

C程序: Simple math program

android-ndk - 在 NDK 中包含库时出错

c++ - Linux、Clang、Cmake、QtCreator : Using shared libraries