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

2024-01-09

我在 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 真正想要的,但如果有人在这里找到真正想要传递字节数组的方法,一种方法似乎是构建一个由字节数组内存支持的 ctypes.c_char ,然后将其传递 https://mail.python.org/pipermail/python-list/2010-January/563875.html.

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

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ctypes 将 byteArray 传递到以 char* 作为参数的 C 函数中? 的相关文章

随机推荐