我尝试使用pybd11和AM使用pybind11-multiprocessing-hangs实现C++到python。不同之处在于,我想在C++中使用Python对象,并从C++中继续调用类方法。代码如下:
#ifdef _WIN32
#include "direct.h"
#define PATH_SEP '\\'
#define GETCWD _getcwd
#define CHDIR _chdir
#else
#include "unistd.h"
#define PATH_SEP '/'
#define GETCWD getcwd
#define CHDIR chdir
#endif
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
using namespace py::literals;
bool ChangeDirectory(const char* dir) { return CHDIR(dir) == 0; }
int wmain(int argc, wchar_t** argv)
{
py::initialize_interpreter();
PySys_SetArgv(argc, argv);
std::string pyCode = std::string(R"(
import os
import sys
from queue import Empty, Full
from multiprocessing import Queue as mQueue, Process as mProcess
import sys
sys.executable = "C:\\Users\\nb\\scoop\\apps\\python\\current\\python.exe"
__file__ = "D:\\sw\\run.py"
print("Hello stackoverflow!", file=open("output.txt", "a"))
class C2PyMulti(object):
"""docstring for TactileEngine"""
def __init__(self):
self.te_ops = MultiProcessTest()
def compose(self,data):
self.te_ops.load_q(data)
class MultiProcessTest(object):
def __init__(self):
self.my_q = mQueue()
self.spawn_processes()
def load_q(self, data):
self.my_q.put(('print',data))
def spawn_processes(self):
args = (self.my_q,'inside message_coordinator')
self.message_coordinator = mProcess(target=message_coordinator, args=args)
try:
# Starts the data processor
val = self.message_coordinator.start()
if val == 1:
self.message_coordinator.join()
except Exception:
print('failed spawn!')
def message_coordinator(mQ,num):
print(num)
while True:
try:
command, args= mQ.get(timeout=.0001)
if command == 'print':
print(args, file=open("output.txt", "a"))
elif command == 'end':
return 1
except (Empty):
pass
cpy2 = C2PyMulti()
cpy2.compose('hello')
cpy2.compose('hello')
cpy2.compose('hello')
cpy2.compose('hello')
cpy2.compose('end')
del cpy2
)");
try
{
FILE* f = nullptr;
fopen_s(&f, "D:\\sw\\run.py", "wt");
fprintf(f, "%s", pyCode.c_str());
fclose(f);
ChangeDirectory("D:\sw\run.py");
//py::module C2py = py::module::import("run"); ///does not work can't find the module
//py::object C2PyMulti = C2py.attr("C2PyMulti");
//py::object c2py = C2PyMulti();
//c2py.attr("load_q")("hello");
py::exec(pyCode);
}
catch (const std::exception & e) {
std::cout << e.what();
}
py::finalize_interpreter();
}
下面是output.txt
的输出:
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
Hello stackoverflow!
最后,我想使用类似于以下内容的内容:
py::module C2py = py::module::import("C2PyMulti");
py::object C2PyMulti = C2py.attr("C2PyMulti");
py::object c2py = C2PyMulti();
c2py.attr("load_q")("hello");
我的任命提前了
因此,为了回答这个问题,我需要分离message_coordinator方法,并通过另一个线程调用它,如:
并通过
std::thread ti(message, C2py, q);
调用它,因此最终结果是:相关问题 更多 >
编程相关推荐