从Python输出数组值然后通过C ++获取它们的好方法?

时间:2012-04-09 20:02:35

标签: c++

由于C ++的烦人溢出问题,我想用Python来预先计算一些值。我有一个函数f(a,b)然后会吐出一个值。我希望能够根据a和b的范围将所需的所有值输出到文件中,然后在C ++中读取该文件并使用流行的矢量或数组或其他更好的方法。

  1. 在?
  2. 中输出f(a,b)的好格式是什么?
  3. 读回C ++的最佳方法是什么?
  4. Vector或multidim数组?

3 个答案:

答案 0 :(得分:1)

您可以使用Python编写与C ++源语法兼容的.h文件。

h_file.write('{')
for a in range(a_size):
    h_file.write('{' + ','.join(str(f(a, b)) for b in range(b_size)) + '},\n')
h_file.write('}')

您可能希望修改该代码以引入一些额外的换行符,事实上我有这样的代码,我稍后可以显示(现在无法访问它)。

答案 1 :(得分:0)

如果有兆字节的数据,那么我会通过内存映射数据文件读取数据,只读。我会安排一些事情,这样我就可以直接使用数据文件,而无需在启动时全部阅读。

这样做的原因是,如果您只想使用某些值,则不希望在启动时读取数兆字节的数据。通过使用内存映射,您的操作系统将自动只读取您需要的文件部分。如果RAM不足,您的操作系统可以重用为该文件分配的内存,而不必浪费时间将其写入交换文件。

如果函数的输出是单个数字,您可能只需要一个整数数组。你可能想要一个2D数组,例如:

#define DATA_SIZE (50 * 25)
typedef const int (*data_table_type)[50];
int fd = open("my_data_file.dat", O_RDONLY);
data_table_type data_table = (data_table_type)mmap(0, DATA_SIZE,
                                  PROT_READ, MAP_SHARED, fd, 0);
printf("f(5, 11) = %d\n", data_table[5][11]);

有关内存映射文件的详细信息,请参阅Wikipediathe UNIX mmap() functionWindows CreateFileMapping() function

如果您需要更复杂的数据结构,可以将C / C ++结构和数组放入文件中。但是你不能嵌入指针或任何具有虚拟内容的C ++类。

一旦您决定了如何阅读数据,下一个问题就是如何生成数据。 struct.pack()对此非常有用 - 它允许您将Python值转换为格式正确的Python字符串,然后您可以将其写入文件。

答案 2 :(得分:0)

您可以使用Python编写包含数据的C ++源代码。 E.g:

def f(a, b):
    # Your function here, e.g:
    return pow(a, b, 65537)
num_a_values = 50
num_b_values = 50
# Write source file
with open('data.cpp', 'wt') as cpp_file:
    cpp_file.write('/* Automatically generated file, do not hand edit */\n\n')
    cpp_file.write('#include "data.hpp"\n')
    cpp_file.write('const int f_data[%d][%d] =\n'
                       % (num_a_values, num_b_values))
    cpp_file.write('{\n')
    for a in range(num_a_values):
        values = [f(a, b) for b in range(num_b_values)]
        cpp_file.write('  {' + ','.join(map(str, values)) + '},\n')
    cpp_file.write('}\n')
# Write corresponding header file
with open('data.hpp', 'wt') as hpp_file:
    hpp_file.write('/* Automatically generated file, do not hand edit */\n\n')
    hpp_file.write('#ifndef DATA_HPP_INCLUDED\n')
    hpp_file.write('#define DATA_HPP_INCLUDED\n')
    hpp_file.write('#define NUM_A_VALUES %d\n' % num_a_values)
    hpp_file.write('#define NUM_B_VALUES %d\n' % num_b_values)
    hpp_file.write('extern const int f_data[%d][%d];\n'
                              % (num_a_values, num_b_values))
    hpp_file.write('#endif\n')

然后,您将生成的源代码编译为项目的一部分。然后,您可以通过#include标头并直接访问f_data[]数组来使用它。

这适用于中小型数据表,例如图标。对于较大的数据表(数百万条目),某些C编译器会失败,您可能会发现编译/链接速度慢得令人无法接受。

如果您的数据更复杂,您可以使用相同的方法来定义结构。

[根据Mark Ransom的回答,但有一些风格差异和更多解释]。