我只是在 python 中打印 car1.vehicle_id 的值。我希望它在前 2 秒打印“1234”,然后当另一个线程中的值更改为“4543”时,更改应该在 python 中生效。这是可能的还是有一个简单的例子可以帮助我解决这个问题?
C++
#include <pybind11/embed.h> #include <string> #include <thread> #include <chrono> // Define namespace for pybind11 namespace py = pybind11; class Vehiclee { // Access specifier public: Vehiclee(){}; ~Vehiclee() {} // Data Members int vehicle_id; std::string vehicle_name; std::string vehicle_color; // Member Functions() void printname() { std::cout << "Vehicle id is: " << vehicle_id; std::cout << "Vehicle name is: " << vehicle_name; std::cout << "Vehicle color is: " << vehicle_color; } }; PYBIND11_EMBEDDED_MODULE(embeded, m){ py::class_(m, "Vehiclee") .def_readonly("vehicle_name", &Vehiclee::vehicle_name) .def_readonly("vehicle_color", &Vehiclee::vehicle_color) .def_readonly("vehicle_id", &Vehiclee::vehicle_id); } py::scoped_interpreter python{}; Vehiclee car1; void threadFunc() { sleep(2); std::cout<<"entering thread"; car1.vehicle_id = 4543; std::cout<<"Modified val in thread"; } int main() { // Initialize the python interpreter // Import all the functions from scripts by file name in the working directory auto simpleFuncs = py::module::import("simpleFuncs"); // Test if C++ objects can be passed into python functions car1.vehicle_id = 1234; std::thread t1(threadFunc); simpleFuncs.attr("simplePrint")(car1); t1.join(); return 0; }
Python
> import time
> import importlib
> import embeded
>
> def simplePrint(argument):
> while(1):
> importlib.reload(embeded)
> print(argument.vehicle_id) time.sleep(1)
电流输出
总是 1234
所需输出
1234 (for first 2 secs)
4543 (after 2 secs)