0

I'm new to using SWIG, and I ran into a few difficulties, trying to send a pointer to function and running it, and specifically running it in a new thread.

I have seen a few question regarding the pointer to function but couldn't figure out the guiding principle for it's use, and i'm pretty sure running it in a new thread will crate more problems as well.

This is my code:

#.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); 

}

my .i file

/* 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*>;

and my python file i'm running

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)

The last line throws an error, obviously can't send the CB this way.

I did manage to use callbacks if they are written in the cpp/h files, but i would like to run python callback functions.

Thanks for any help!

Mumfordwiz
  • 1,483
  • 4
  • 19
  • 31
  • Passing a Python callback to a C++ function is non-trival, but it can be done. See this answer: http://stackoverflow.com/a/11522655/235698 – Mark Tolonen Feb 23 '17 at 06:42
  • The problem that you're really going to hit, even once you get callbacks working is that you'll have to hold the [Python GIL (global interpreter lock)](https://wiki.python.org/moin/GlobalInterpreterLock) to actually be able to do anything useful inside your Python, so you could still serialise everything you do down to a single thread of execution with not change performance. – Flexo Feb 23 '17 at 08:06
  • So unless your code in the real threads is mostly C++ with a few occasional calls to Python I think you're not going to end up with this achieving what it looks like you're trying to do. – Flexo Feb 23 '17 at 08:08

0 Answers0