Created
October 5, 2011 22:09
-
-
Save bfroehle/1265889 to your computer and use it in GitHub Desktop.
Boost.Python from Python to FILE* wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <boost/python.hpp> | |
#include <iostream> | |
namespace { | |
void *convert_to_FILEptr(PyObject* obj) { | |
return PyFile_Check(obj) ? PyFile_AsFile(obj) : 0; | |
} | |
} | |
void test_argument(FILE* f) { | |
fprintf(f, "Written from C++\n"); | |
} | |
void test_extract(boost::python::object obj) { | |
PyObject_Print(obj.ptr(), stdout, 0); | |
boost::python::extract<FILE*> get_file(obj); | |
if (get_file.check()) | |
std::cout << " can be converted to FILE*" << std::endl; | |
else | |
std::cout << " is not a FILE*" << std::endl; | |
} | |
BOOST_PYTHON_MODULE(file_wrapper) { | |
boost::python::converter::registry::insert | |
(convert_to_FILEptr, | |
boost::python::type_id<FILE>(), | |
&boost::python::converter::wrap_pytype<&PyFile_Type>::get_pytype); | |
boost::python::def("test_argument", &test_argument); | |
boost::python::def("test_extract", &test_extract); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import file_wrapper | |
with open('test.txt', 'rw') as f: | |
# Use the Boost.Python argument to FILE* converter. | |
file_wrapper.test_argument(f) | |
# Read the results. | |
f.seek(0) | |
print f.readline() | |
# Test using extract<FILE*> | |
file_wrapper.test_extract(None) | |
file_wrapper.test_extract(f) | |
file_wrapper.test_extract(45) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment