如何在pybind11中调用Python内置方法(如open)?
open Function Directly in pybind11 Got it, I totally get why you'd want to call Python's built-in open directly from C++ via pybind11 instead of wrapping it in a separate Python file—keeps everything self-contained and plays to pybind11's strength of bridging C++ and Python natively. Here's a step-by-step breakdown with code examples:
Core Concept
Python's built-in functions (like open, print, len) live in the __builtins__ module. Pybind11 lets you import this module directly, grab the open function as a Python object, and invoke it just like you would in Python.
Full Code Example
Here's a complete pybind11 module function that demonstrates opening a file, reading its content, and handling basic errors:
#include <pybind11/pybind11.h> #include <string> namespace py = pybind11; PYBIND11_MODULE(builtin_demo, m) { m.def("read_file_with_python_open", [](const std::string& filename) -> std::string { try { // 1. Import the __builtins__ module py::module_ builtins = py::module_::import("__builtins__"); // 2. Get the built-in open function py::object open_func = builtins.attr("open"); // 3. Call open() just like in Python: open(filename, mode) py::object file_obj = open_func(filename, "r"); // 4. Call read() on the file object py::str file_content = file_obj.attr("read")(); // 5. Close the file (or use a try-finally to ensure cleanup) file_obj.attr("close")(); // Convert Python string to C++ string and return return file_content.cast<std::string>(); } catch (const py::error_already_set& e) { // Propagate Python exceptions back to the Python caller throw; } }, "Read a file using Python's built-in open function"); }
Key Details
- Importing
__builtins__: This module contains all of Python's default built-in functions and types, so you don't need any extra imports in Python or C++. - Calling the
openfunction: Theopen_funcobject acts exactly like Python'sopen—you pass arguments (filename, mode) just as you would in Python code. - Working with the file object: Once you have the file object, you can call its methods (like
read(),write(),close()) usingpy::object.attr("method_name")(). - Error handling: Wrapping the code in a
try-catchblock forpy::error_already_setensures that Python exceptions (likeFileNotFoundError) are propagated back to the Python runtime instead of crashing your C++ code.
Alternative: Using Python's Context Manager (with Statement)
If you want to mimic Python's with open(...) as f: pattern to automatically close the file, you can use pybind11's py::with helper (available in newer versions):
// Inside the try block: py::object file_obj = open_func(filename, "r"); return py::with(file_obj, [&](py::object f) { py::str file_content = f.attr("read")(); return file_content.cast<std::string>(); });
This ensures the file is closed automatically when the with block exits, even if an error occurs.
内容的提问来源于stack exchange,提问作者Markyroson

