如何使用ctypes的为ByteArray传递到一个C函数,它接受一个char *作为它的参数? [英] How can I use ctypes to pass a byteArray into a C function that takes a char* as its argument?

查看:963
本文介绍了如何使用ctypes的为ByteArray传递到一个C函数,它接受一个char *作为它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个在C函数,它接受一个int的大小和一个char *缓冲区作为参数。我想用ctypes的从蟒蛇调用这个函数,并传递一个Python的字节数组。我知道,首先你必须编译C文件到共享库(.so文件),并使用ctypes的调用该函数。这里的code我有这么远。

I have created a function in C which takes an int size and a char *buffer as arguments. I would like to use ctypes to call this function from python and pass in a python byteArray. I know that first you must compile the C file into a shared library (.so file) and use ctypes to call that function. Here's the code I have so far.

encrypt.c:

encrypt.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);
    }
}

和这里的蟒蛇文件:

import ctypes

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

基本上,我想打电话从蟒蛇的C法,通过一条巨蟒字节数组,并将它通过遍历数组并打印每个元素

Basically I want to call the C method from python, pass through a python byte array, and have it iterate through the array and print each element

推荐答案

您所需要的最低(Python 2里)是:

The minimum you need (Python 2) is:

hello = "hello"
encryptPy.encrypt(5,hello)
encryptPy.decrypt(5,hello)

不过,这是好事,声明参数类型和返回值也是如此。全程式:

But it is good to declare the argument types and return values as well. Full program:

#!python2
import ctypes

encryptPy = ctypes.CDLL('/home/aradhak/Documents/libencrypt.so')

encryptPy.encrypt.argtypes = (ctypes.c_int,ctypes.c_char_p)
encryptPy.encrypt.restype = None
encryptPy.decrypt.argtypes = (ctypes.c_int,ctypes.c_char_p)
encryptPy.decrypt.restype = None

hello = "hello"
encryptPy.encrypt(len(hello),hello)
encryptPy.decrypt(len(hello),hello)

注意,传递一个Python字节字符串时,考虑缓冲区不变。在这种情况下,你只正在阅读的缓冲区,但如果你需要允许C函数突变字符串使用:

Note that when passing a python byte string, consider the buffer immutable. In this case you only are reading the buffer, but if you need to allow the C function to mutate the string use:

hello = ctypes.create_string_buffer(5,'hello')

本作品为好,但将长度为6终止空将包括在内。

This works as well, but will be length 6. A terminating null will be included.

hello = ctypes.create_string_buffer('hello')

这篇关于如何使用ctypes的为ByteArray传递到一个C函数,它接受一个char *作为它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆