在Python数组和.NET数组之间转换

5 投票
1 回答
8265 浏览
提问于 2025-04-15 23:50

我有一个Python的方法,它返回一个Python的字节数组,类型是array('c')。

现在,我想用System.Runtime.InteropServices.Marshal.Copy来复制这个数组。不过,这个方法需要一个.NET的数组。

import array
from System.Runtime.InteropServices import Marshal

bytes = array.array('c')
bytes.append('a')
bytes.append('b')
bytes.append('c')
Marshal.Copy(bytes, dest, 0, 3)

有没有办法在不复制数据的情况下让它工作?如果不行的话,我该怎么把Python数组里的数据转换成.NET数组呢?

1 个回答

7

要把一个Python数组转换成.NET数组,可以参考下面的代码:

import array
from System import Array, Char

x = array.array('c', 'abc')

y = Array[Char](x)

这里有一些关于在IronPython中创建类型数组的信息:

http://www.ironpython.info/index.php?title=Typed_Arrays_in_IronPython

撰写回答