如何将 Python 列表格式化为初始化的 C 数组?

How do I format a Python list as an initialized C array?

我需要为用 C 编写的嵌入式固件生成一个查找 table。生成 Python 中的值很容易,但是我如何以 C 编译器将要输出的形式输出这些值接受?

例如,我想要这样的东西:

>>> a = range(0,20)
>>> print(to_c_array(a))
int table[] = {
    0, 1, 2, 3, 4, 5, 6, 7,
    8, 9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19};

这里有一个函数可以满足您的要求:

def to_c_array(values, ctype="float", name="table", formatter=str, colcount=8):
    # apply formatting to each element
    values = [formatter(v) for v in values]

    # split into rows with up to `colcount` elements per row
    rows = [values[i:i+colcount] for i in range(0, len(values), colcount)]

    # separate elements with commas, separate rows with newlines
    body = ',\n    '.join([', '.join(r) for r in rows])

    # assemble components into the complete string
    return '{} {}[] = {{\n    {}}};'.format(ctype, name, body)

... 以及如何使用它生成伽玛校正的示例 查找 table:

>>> gamma = 0.3
>>> N = 32
>>> values = [math.pow(float(i)/N, gamma) for i in range(N)]
>>> print(to_c_array(values, ctype='float', name='gamma', formatter=lambda x: '{:0.5f}'.format(x)))
float gamma[] = {
    0.00000, 0.35355, 0.43528, 0.49158, 0.53589, 0.57299, 0.60520, 0.63385,
    0.65975, 0.68348, 0.70543, 0.72589, 0.74509, 0.76320, 0.78036, 0.79668,
    0.81225, 0.82716, 0.84147, 0.85523, 0.86849, 0.88129, 0.89368, 0.90568,
    0.91731, 0.92862, 0.93961, 0.95031, 0.96073, 0.97090, 0.98082, 0.99052};