我使用^ {CD1>}来转换一个二进制文件中的一些信息,这些文件需要被C++程序读取。此文件将包含带字符串的行和其他带double/vectors的行
当我试图读取C++中的一个向量的时候,问题就出现了:向量的地址在行的末尾,地址有11个字符,而C++中有8个字符。当我尝试直接读取向量到C++中时,由于这个差异而发生错误。一种可能的解决方案是逐元素读取向量,但这会降低性能
有没有可能在转换和读取过程中撕开地址,或者忽略地址,同时删除整个向量
下面是我们测试的一些代码:
C++ DLL模块:
#include<iostream>
#include<fstream>
#include<cstring>
#include <typeinfo>
using namespace std;
#define DLLEXPORT extern "C" __declspec(dllexport)
struct new_element {
int id;
unsigned int n_measures;
double* value;
};
DLLEXPORT int writer_bin_file_c(const char* file_path, new_element structed_data)
{
try {
ofstream output_file(file_path);
output_file.write((char*)&structed_data, sizeof(structed_data));
output_file << &structed_data;
output_file.close();
} catch (...) {
return -1;
}
return 0;
}
DLLEXPORT new_element reader_bin_file_c(const char* file_path, new_element structed_data)
{
try {
ifstream input_file(file_path, ios::binary);
input_file.read((char*)&structed_data, sizeof(structed_data));
input_file.close();
} catch (...) {
cout << "Error ao ler o arquivo" << endl;
}
return structed_data;
}
Python写入文件:
from ctypes import *
import sys
import numpy as np
lib = CDLL("version4/template_file.so")
class new_element(Structure):
_fields_ = [("id", c_int),
("n_measures", c_uint),
("value", POINTER(c_double))]
template_file = lib
new_element_pointer = POINTER(new_element)
writer_bin_file = template_file.writer_bin_file_c
writer_bin_file.argtypes = [c_char_p, new_element]
writer_bin_file.restype = c_void_p
reader_bin_file_c = template_file.reader_bin_file_c
reader_bin_file_c.restype = new_element
tam = 10
medida = np.arange(tam, dtype=c_double)
medida = medida.ctypes.data_as(POINTER(c_double))
element = new_element(4, tam)
element.value = medida
file_out = b'version4/element.txt'
answer = writer_bin_file(file_out, element)
C++阅读文件:
#include<iostream>
#include<fstream>
#include<cstring>
#include <typeinfo>
using namespace std;
struct new_element {
int id;
unsigned int n_measures;
double* value;
};
new_element reader_bin_file(const char* file_path, new_element structed_data)
{
try {
ifstream input_file(file_path);
input_file.read((char*)&structed_data, sizeof(structed_data));
input_file.close();
} catch (...) {
cout << "Error ao ler o arquivo" << endl;
}
return structed_data;
}
int main(int argc, char const *argv[])
{
new_element read_template;
read_template = reader_bin_file(file_out, read_template);
cout << "ID: " << read_template.id << endl;
cout << "n_measures: " << read_template.n_measures << endl;
cout << "Value: ";
for (int i = 0; i < read_template.n_measures; i++)
{
cout << "( " << i << " ): " << read_template.value[i] << " | ";
}
cout << endl;
return 0;
}
你有一个很深的误解
一对字段
是一个数组(从其名称推断),因此在writer中必须保存
n_measures
个双值,而不是一个指针。因此,在读取器中,您应该读取n_measures
值,而不仅仅是指针。指针只是内存空间中的一个索引,而不是一些“万能”的C/C++语言特性,它可以保存您所需要的一切所以,在C++编写代码中执行
}
希望你能得到这个想法,至少在C++部分上是这样。读取器代码类似-读取id
、n_measures
,然后分配values
数组并逐个读取值相关问题 更多 >
编程相关推荐