2013-02-11 64 views
0

我有升壓轉換在Python到C一些二進制++ :: python.The二進制可能來自於圖像或文字file.But一些錯誤發生的圖像轉換文件的二進制文件轉換爲C++。以下是一個例子。關於Boost.Python的Python的二進制轉換成C++二進制A錯誤

C++

#include <boost/python.hpp> 
#include <boost/python/module.hpp> 
#include <boost/python/def.hpp> 
#include <fstream> 
#include <iostream> 

using namespace boost::python; 
void greet(char *name,char *ss) 
{ 
    std::ofstream fout(name,std::ios::binary); 
    std::cout<< "This length is:" << strlen(ss) <<std::endl; 
    fout.write(ss.strlen); 
    fout.close(); 
    return; 
} 

BOOST_PYTHON_MODULE(ctopy) 
{ 
    def("greet",greet); 
} 

蟒蛇:

import ctopy 
#It is right. 
f=open("t1.txt","rb") 
ctopy.greet("t2.txt",f.read()) 
f.close() 

#Do a error.There isn't data in the file "p2.jpg". 
f2=open("p1.jpg","rb") 
ctopy.greet("p2.jpg",f2.read()) #error.the file "p2.jpg" will be a empty file. 
f2.close() 

如何圖像的二進制轉換爲C++?

+0

你的問題根本不清楚,你正試圖完成什麼樣的**,發生了什麼錯誤?用所需信息編輯您的問題。 – StoryTeller 2013-02-11 14:55:57

+0

@ StoryTeller,我寫了更多。它會在最後的python代碼中創建一個錯誤文件。 – simon 2013-02-11 15:15:41

回答

0

請提供真正的代碼,你從它創建了一個小例子之後。此外,你使用的是哪個Python版本?總之,這裏的幾件事情是錯誤的,你提供的代碼:

  • 你應該使用const,因爲任何C++ FAQ會告訴你。
  • 您正在使用一些東西,甚至不保證是零終止,但它可以很好地包含在中間零的strlen()。
  • 您應該使用的std :: string,如果你有內部空字符不BARF。
  • 關閉文件是無用的,這是在dtor中自動完成的。沖洗和檢查流狀態更有趣。失敗時,拋出異常。
  • 拖放尾隨回報,它不會傷害,但它是不必要的噪音。
  • 閱讀PEP 8
  • 使用帶語句讀取文件。
+0

謝謝。這是一個非常好的答案。 – simon 2013-02-12 03:19:42

1

一個binary file的編碼通常取決於比編程語言的其他因素,諸如文件,操作系統等。例如類型,上POSIX,文本文件包含組織成零個或多個字符行,它在C++和Python中都以相同的方式表示。這兩種語言只需要使用給定格式的正確編碼。在這種情況下,在將Python二進制流轉換爲C++二進制流時沒有特殊的過程,因爲它是兩種語言的原始字節流。

有兩個問題與原代碼的方法:

  • strlen()應該被用來確定一個空值終止字符串的長度。如果二進制文件包含值爲\0的字節,則strlen()將不會返回數據的整個大小。因爲char*代替std::string
  • 的數據的大小都將丟失。請考慮使用std::string,因爲它通過size()提供了兩個大小,並允許字符串本身內爲空字符。另一種解決方案是明確提供數據的大小和數據。

下面是一個完整的推動作用。Python的例子:

#include <boost/python.hpp> 
#include <fstream> 
#include <iostream> 

void write_file(const std::string& name, const std::string& data) 
{ 
    std::cout << "This length is: " << data.size() << std::endl; 
    std::ofstream fout(name.c_str(), std::ios::binary); 
    fout.write(data.data(), data.size()); 
    fout.close(); 
} 

BOOST_PYTHON_MODULE(example) 
{ 
    using namespace boost::python; 
    def("write", &write_file); 
} 

而且例如Python代碼(test.py):

import example 

with open("t1.txt", "rb") as f: 
    example.write("t2.txt", f.read()) 

with open("p1.png", "rb") as f: 
    example.write("p2.png", f.read()) 

和使用,在這裏我下載this圖像,並創建一個簡單的文本文件,然後創建它們與副本以上代碼:

[twsansbury]$ wget http://www.boost.org/style-v2/css_0/get-boost.png -O p1.png >> /dev/null 2>&1 
[twsansbury]$ echo "this is a test" > t1.txt 
[twsansbury]$ ./test.py 
This length is: 15 
This length is: 27054 
[twsansbury]$ md5sum t1.txt t2.txt 
e19c1283c925b3206685ff522acfe3e6 t1.txt 
e19c1283c925b3206685ff522acfe3e6 t2.txt 
[twsansbury]$ md5sum p1.png p2.png 
fe6240bff9b29a90308ef0e2ba959173 p1.png 
fe6240bff9b29a90308ef0e2ba959173 p2.png

md5校驗和匹配,表示文件內容相同。

+0

謝謝。但只有一位答辯人。@ doomster先回答這個問題。 – simon 2013-02-12 03:18:07