簡體   English   中英

如何將字節緩沖區從 Python 傳遞到 C

[英]How to pass Bytes buffer from Python to C

我正在試驗 Python 中的原生 C 擴展。 我現在要完成的是將字節緩沖區從 Python 傳遞到 C。

我需要從磁盤加載一個二進制文件並將該緩沖區傳遞給 C 擴展,但是我不知道應該使用什么類型。 我現在擁有的是:

Python 部分:

import ctypes

lib = ctypes.cdll.LoadLibrary("lib.so")

f = open("file.png", "rb")
buf = f.read()
f.close()

lib.func(buf)

C 部分:

#include <stdio.h>

void func(int buf) {
    // do something with buf
}

將二進制數據和長度傳遞給 C function 的示例解決方案將其轉儲。

Python 部分:

import ctypes

lib = ctypes.cdll.LoadLibrary("./lib.so")
f = open("file.png", "rb")
buf = f.read()
f.close()

lib.func.argtypes = [ctypes.c_void_p, ctypes.c_uint]
lib.func(ctypes.cast(buf, ctypes.c_void_p), len(buf))

C 部分:

#include <stdio.h>

void func(unsigned char *buf, unsigned int len) {
    if (buf) {
        for (unsigned int i=0; i<len; i++) {
            if (i%16 == 0) {
                printf("\n");
            }
            printf("0x%02x ", buf[i]);
        }
        printf("\n");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM