如何通过引用将“原始”变量和“类”对象从C ++传递到Python

时间:2018-12-02 14:57:06

标签: python c++ multithreading

我在Python中具有如下功能:

import time

def getInteger(a, b):    
    print ('Working ...', a, b)
    while a < 5:
        time.sleep(1)
        print('waiting')
        pass    
    print ('DONE', a, b)
    c = a * b
    print (c)       
    return c

我在线程中从C ++代码调用getInteger(a, b)函数(使用this),如下所示:

#include <time.h>
#include <iostream>
#include <thread>

#include <Python.h>
#include "pyhelper.hpp"

void thread_python(long *a, long *b);

int main(){
    _putenv_s("PYTHONPATH", ".");

    long a = 4;
    long b = 5;

    std::thread t(thread_python, &a, &b);

    std::this_thread::sleep_for(std::chrono::milliseconds(3000));

    a = 10;
    std::cout << a << "\t a -> changed\n";

    t.join();
    system("pause");
    return 0;
}

void thread_python(long *a, long *b) {
    std::cout << *a << "\t" << *b << "\n";
    CPyInstance hInstance;

    CPyObject pName = PyUnicode_FromString("tst");
    CPyObject pModule = PyImport_Import(pName);
    CPyObject pValue;   

    CPyObject pArgs = PyTuple_New(2);       

    int result = 0;

    CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger");        
    if (pFunc && PyCallable_Check(pFunc)){                                  
        PyTuple_SetItem(pArgs, 0, PyLong_FromLong(*a));
        PyTuple_SetItem(pArgs, 1, PyLong_FromLong(*b));     

        pValue = PyObject_CallObject(pFunc, pArgs);             
        result = PyLong_AsLong(pValue);         
    }
}

但是正如您在代码中看到的,a的值将在一段时间后发生变化。

我如何制作Python代码来实现此更改并完成while循环并打印c的值?

此外,如何将我的“类”和“结构”对象传递给python函数或方法?

0 个答案:

没有答案