0
我有一个使用boost python的C++类。我正在尝试使用pthread从C++的线程运行python代码。问题是下面的代码没有产生任何输出。我期待stdout输出John DOE
。看起来&this->instance
不包含在对象内部设置的值。如何将当前对象或其实例变量传递给pthread_create
,以便pthread
能够看到正在传递的内容?pthread没有看到作为参数传递的实例变量
Python:
class A:
def __init__(self, name):
self.name = name
def printName(self, lastName):
print self.name + " " + lastName
C++:
#include <boost/python.hpp>
#include <string.h>
#include <pthread.h>
using namespace std;
using namespace boost::python;
class B {
public:
object instance;
B();
void setupPython();
static void *runPython(void *);
};
B::B() {
Py_Initialize();
}
void B::setupPython() {
pthread_t t1;
try {
object a = import("A");
instance = a.attr("A")("John");
pthread_create(&t1, NULL, runPython, &this->instance); // THIS IS PROBLEM
}
catch(error_already_set const &) {
PyErr_Print();
}
}
void *B::runPython(void *instance) {
((object *)instance)->attr("printName")("DOE");
}
int main() {
B b;
b.setupPython();
}
谢谢。
*尝试在堆中分配B和检查是否正常工作:*仍可能会无法正常工作 - 当'main()的返回' ,程序结束。 –
@AndrewHenle正确,编辑答案。 – Steeve
@Steeve谢谢你的回答。有用。 – pseudo