Skip to content

Instantly share code, notes, and snippets.

@bfroehle
Created October 5, 2011 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfroehle/1265889 to your computer and use it in GitHub Desktop.
Save bfroehle/1265889 to your computer and use it in GitHub Desktop.
Boost.Python from Python to FILE* wrapper
#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);
}
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