SWIG - 在新线程

时间:2017-02-23 06:23:56

标签: python c++ multithreading swig

我是使用SWIG的新手,我遇到了一些困难,尝试发送指向函数并运行它的指针,并专门在新线程中运行它。

我已经看到了一些关于功能指针的问题,但无法弄清楚它的使用指导原则,而且我很确定在一个新线程中运行它会更多问题也是如此。

这是我的代码:

#.h file
#include <vector>
#include <memory>
class Die
{
public:
    Die();
    Die(int a);
    ~Die();
    int foo(int a) ;
    std::vector<int> foo2(int b) ;
    std::shared_ptr<Die> getDie(int a);
    void funcTest(void* (*foo5)(void*), int a);
    int myVar;
};

#.cpp file

#include <iostream>
#include <string>
#include <stdint.h>
#include <pthread.h>

#include "example.h"
int Die::foo(int a) {

    std::cout << "foo: running example" <<std::endl;

    return 1;
}

std::vector<int> Die::foo2(int b) {
    std::cout << "foo2: running foo2" <<std::endl;
    std::vector<int> v;
    v.push_back(1);
    v.push_back(b);
    std::cout<< myVar;
    return v;
}
Die::Die(){}
Die::Die(int a){myVar = a;}
Die::~Die(){}
std::shared_ptr<Die> Die::getDie(int a) {
    return std::make_shared<Die> (a);
}

void Die::funcTest(void* (*foo5)(void*), int a){
    pthread_t mThread;
    int p = 2;
    pthread_create(&mThread, NULL, foo5, &p); 

}

我的.i文件

/* File: example.i */
%module example
%include "stdint.i"
%include "std_vector.i"
%include <std_shared_ptr.i>
%shared_ptr(Die)
%{
#include "example.h"

%}
%include "example.h"

/*void Die::funcTest(void* (*foo5)(void*), int a);*/
%template(DieVector) std::vector<Die*>;

我的python文件正在运行

import example as e

def testCB(a, b):
    print "running in CB: " +str(b)
    # what can I do with a


d = e.Die()
p = d.getDie(2)
print "hello i'm here"
p.foo2(4)
d.funcTest(testCB, 4)

最后一行引发错误,显然无法以这种方式发送CB。

如果用cpp/h文件编写,我确实设法使用回调,但我想运行python回调函数。

感谢您的帮助!

0 个答案:

没有答案