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