- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 Python 应用程序中,我有一个包含一些数据的字节数组。我的python代码由一些外部 native 库(DLL/so/dylib)调用(使用ctypes及其 callback functions )。回调函数之一包括指向在该外部库中分配的非托管缓冲区的指针。
我需要将字节数组的一部分复制到此非托管缓冲区中,或将非托管缓冲区的内容复制到特定位置的字节数组中。
简单来说,我有
def copy_from_python_callback(c_void_p_parameter : c_void_p, offset : int, size : int):
managed_buf = bytearray(some_size) # suppose we have data in this buffer already
unmanaged_buf = c_void_p_parameter
# what do I need to do here?
# src_buf = pointer_to_specific_byte_in_managed_buf
memmove(unmanaged_buf, src_buf, size)
def copy_to_python_callback(c_void_p_parameter : c_void_p, offset : int, size : int):
managed_buf = bytearray(some_size) #some_size is assumed to be larger than offset + size
unmanaged_buf = c_void_p_parameter
# what do I need to do here?
# dst_buf = pointer_to_specific_byte_in_managed_buf
memmove(dst_buf, unmanaged_buf, size)
在其他语言中,答案很简单 - 我要么调用专用方法(例如在 .NET Framework 的 Marshal 类中),要么获取指向字节数组中特定字节的指针(在 C++ 或 Pascal 等 native 语言中) )并完成。不幸的是,我不知道如何在没有中间 bytes() 或类似缓冲区的情况下在 Python 中执行这些操作。
我有一些使用中间 bytes() 实例的方法,但是仅仅因为无法获取指针而复制数据对我来说似乎很奇怪。
如果可能的话,我正在寻找与版本无关的解决方案,但也可以使用仅包含 python3 的解决方案。先感谢您。
最佳答案
列出 [Python.Docs]: ctypes - A foreign function library for Python 。
您正在寻找的东西是可能的。数组(CType)派上用场。
下面是一个“小”示例。出于演示目的,缓冲区仅包含“人类友好的”char。
dll00.c:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#if defined(_WIN32)
# define DLL00_EXPORT_API __declspec(dllexport)
#else
# define DLL00_EXPORT_API
#endif
#define C_TAG "From C - "
typedef int (*ReadFunc)(void *ptr, uint32_t offset, uint32_t size);
typedef int (*WriteFunc)(void *ptr, uint32_t offset, uint32_t size);
#if defined(__cplusplus)
extern "C" {
#endif
DLL00_EXPORT_API int testBufferCallbacks(uint32_t bufSize,
ReadFunc read, uint32_t readOffset, uint32_t readSize,
WriteFunc write, uint32_t writeOffset, uint32_t writeSize);
#if defined(__cplusplus)
}
#endif
void prinBuffer(const uint8_t *buf, uint32_t size) {
printf("%sBuffer (size %d) 0x%016llX\n Contents: ", C_TAG, size, (uint64_t)buf);
for (uint32_t i = 0; i < size; i++) {
printf("%c", ((uint8_t*)buf)[i]);
}
printf("\n");
}
int testBufferCallbacks(uint32_t bufSize,
ReadFunc read, uint32_t readOffset, uint32_t readSize,
WriteFunc write, uint32_t writeOffset, uint32_t writeSize) {
const uint8_t charOffset = 0x41;
void *buf = malloc(bufSize);
uint8_t *cBuf = (uint8_t*)buf;
for (uint32_t i = 0; i < bufSize; i++) {
cBuf[i] = (uint8_t)((i + charOffset) % 0x100);
}
prinBuffer(cBuf, bufSize);
if ((read != NULL) && (readSize > 0)) {
printf("\n%sCalling read(0x%016llX, %u, %u)...\n", C_TAG, (uint64_t)buf, readOffset, readSize);
read(buf, readOffset, readSize);
}
if ((write != NULL) && (writeSize > 0)) {
printf("\n%sCalling write(0x%016llX, %u, %u)...\n", C_TAG, (uint64_t)buf, writeOffset, writeSize);
write(buf, writeOffset, writeSize);
prinBuffer(cBuf, bufSize);
}
if ((read != NULL) && (readSize > 0)) {
printf("\n%sCalling read(0x%016llX, %u, %u)...\n", C_TAG, (uint64_t)buf, readOffset, readSize);
read(buf, readOffset, readSize);
}
prinBuffer(cBuf, bufSize);
free(buf);
printf("\n%sDone.\n", C_TAG);
return 0;
}
code00.py:
#!/usr/bin/env python3
import sys
import ctypes as ct
DLL_NAME = "./dll00.dll"
ReadFunc = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_uint32, ct.c_uint32)
WriteFunc = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_uint32, ct.c_uint32)
def create_bytearray(size, offset_char=0x61):
contents = "".join(chr(i) for i in range(offset_char, offset_char + size))
return bytearray(contents.encode())
def read_c_buf(buf : ct.c_void_p, offset : ct.c_uint32, size : ct.c_uint32):
print("C buf: 0x{0:016X}".format(buf))
ba = create_bytearray(0x1A)
print("Python initial buffer: {0:}".format(ba))
UCharArr = ct.c_uint8 * size
uchar_arr = UCharArr.from_buffer(ba, offset) # Shared memory
ct.memmove(uchar_arr, buf, size)
print("Python final buffer: {0:}\n".format(ba))
return 0
def write_c_buf(buf : ct.c_void_p, offset : ct.c_uint32, size : ct.c_uint32):
print("C buf: 0x{0:016X}".format(buf))
ba = create_bytearray(size + offset, offset_char=0x30 - offset)
print("Python buffer: {0:}\n".format(ba))
UCharArr = ct.c_uint8 * size
uchar_arr = UCharArr.from_buffer(ba, offset) # Shared memory
ct.memmove(buf, uchar_arr, size)
return 0
def main(*argv):
dll00 = ct.CDLL(DLL_NAME)
testBufferCallbacks = dll00.testBufferCallbacks
testBufferCallbacks.argtypes = (ct.c_uint32, ReadFunc, ct.c_uint32, ct.c_uint32, WriteFunc, ct.c_uint32, ct.c_uint32)
testBufferCallbacks.restype = ct.c_int
read_callback = ReadFunc(read_c_buf)
buf_size = 0x1A
read_offset = 10
read_size = 16
write_callback = WriteFunc(write_c_buf)
write_offset = 5
write_size = 10
res = testBufferCallbacks(buf_size, read_callback, read_offset, read_size, write_callback, write_offset, write_size)
print("\n{0:s} returned: {1:d}".format(testBufferCallbacks.__name__, res))
if __name__ == "__main__":
print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32, sys.platform))
rc = main(*sys.argv[1:])
print("\nDone.")
sys.exit(rc)
输出:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q059255471]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###
[prompt]> "c:\Install\x86\Microsoft\Visual Studio Community\2017\VC\Auxiliary\Build\vcvarsall.bat" x64
**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.17
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
[prompt]> dir /b
code00.py
code01.py
dll00.c
[prompt]> cl /nologo /MD /DDLL dll00.c /link /NOLOGO /DLL /OUT:dll00.dll
dll00.c
Creating library dll00.lib and object dll00.exp
[prompt]> dir /b
code00.py
code01.py
dll00.c
dll00.dll
dll00.exp
dll00.lib
dll00.obj
[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code00.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 064bit on win32
From C - Buffer (size 26) 0x0000016BFE546EB0
Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ
From C - Calling read(0x0000016BFE546EB0, 10, 16)...
C buf: 0x0000016BFE546EB0
Python initial buffer: bytearray(b'abcdefghijklmnopqrstuvwxyz')
Python final buffer: bytearray(b'abcdefghijABCDEFGHIJKLMNOP')
From C - Calling write(0x0000016BFE546EB0, 5, 10)...
C buf: 0x0000016BFE546EB0
Python buffer: bytearray(b'+,-./0123456789')
From C - Buffer (size 26) 0x0000016BFE546EB0
Contents: 0123456789KLMNOPQRSTUVWXYZ
From C - Calling read(0x0000016BFE546EB0, 10, 16)...
C buf: 0x0000016BFE546EB0
Python initial buffer: bytearray(b'abcdefghijklmnopqrstuvwxyz')
Python final buffer: bytearray(b'abcdefghij0123456789KLMNOP')
From C - Buffer (size 26) 0x0000016BFE546EB0
Contents: 0123456789KLMNOPQRSTUVWXYZ
From C - Done.
testBufferCallbacks returned: 0
Done.
不用说,超出(C)缓冲区的边界,会产生U未定义的B行为(并且我的代码不执行此类检查)。
关于python - 如何将 bytearray 的一部分复制到 c_void_p 引用的内存,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59255471/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!