簡體   English   中英

如何為Python Swigged C ++對象創建和分配回調函數

[英]How to create and assign a callback function for a Python Swigged C++ object

我有一個悶熱的C ++類(充當具有事件的插件),帶有指向可分配的回調函數的指針,例如

typedef void (*PluginEvent)(void* data1, void* data2);

class PluginWithEvents :  public Plugin
{
    public:
        bool assignOnProgressEvent(PluginEvent pluginsProgress, void* userData1 = nullptr, void* userData2 = nullptr);
        void workProgressEvent(void* data1, void* data2);
    protected:
        PluginEvent mWorkProgressEvent;
        void* mWorkProgressData1;
        void* mWorkProgressData2;
};

和實現代碼

void PluginWithEvents::workProgressEvent(void* data1, void* data2)
{
    if(mWorkProgressEvent)
    {
        mWorkProgressEvent(data1, data2);
    }
}

bool PluginWithEvents::assignOnProgressEvent(PluginEvent progress, void* userData1, void* userData2)
{
    mWorkProgressEvent = progress;
    mWorkProgressData1 = userData1;
    mWorkProgressData2 = userData2;
    return true;
}

問題是,在Python中使用此類時,如何定義要傳遞給AssignProgressEvent函數的回調函數?

以下Python代碼給出了錯誤:

NotImplementedError: Wrong number or type of arguments for overloaded 
function 'PluginWithEvents_assignOnProgressEvent'.

Possible C/C++ prototypes are:
PluginWithEvents::assignOnProgressEvent(dsl::PluginEvent,void *,void *)
PluginWithEvents::assignOnProgressEvent(dsl::PluginEvent,void *)
PluginWithEvents::assignOnProgressEvent(dsl::PluginEvent)

我准備了一個我在評論中提到的例子。 它變得非常可怕,並且可能相當脆弱。 在很多地方,可以大大改善錯誤檢查。

在接口文件中,我包含了后端代碼( test.hpp ),該代碼或多或少是您所提問題中的內容以及我用於Python回調的工具。 所有令人討厭的細節都隱藏在python_callback.hpp

然后,我宣布一個全局變量callback保持目前的回調函數callback_caller它調用回調。 您已經在這里注意到了這種方法的缺點之一。 隨時最多可以有一個回調。 因此,不要將多個回調傳遞給一個函數,也不要保留對callback的引用或指針(復制可能沒問題,但不能保證)。

其余的是將Python函數映射到C ++函數指針的類型映射。


test.i

%module example
%{
#include <iostream>

#include "test.hpp"
#include "python_callback.hpp"

PythonCallback callback;

void callback_caller(void *, void *) {
    double pi = callback.call<double>("ABC", 3.14, 42);
    std::cout << "C++ reveived: " << pi << '\n';
}
%}

%include <exception.i>
%exception {
  try {
    $action
  } catch (std::exception const &e) {
    SWIG_exception(SWIG_RuntimeError, e.what());
  }
}

%typemap(typecheck) PluginEvent {
    $1 = PyCallable_Check($input);

}
%typemap(in) PluginEvent {
    callback = PythonCallback($input);
    $1 = &callback_caller;
}

%include "test.hpp"

test.hpp

#pragma once

typedef void (*PluginEvent)(void *data1, void *data2);

class PluginWithEvents {
public:
    bool assignOnProgressEvent(PluginEvent pluginsProgress,
                               void *userData1 = nullptr,
                               void *userData2 = nullptr) {
        mWorkProgressEvent = pluginsProgress;
        mWorkProgressData1 = userData1;
        mWorkProgressData2 = userData2;
        return true;
    }
    void workProgressEvent(void *data1, void *data2) {
        if (mWorkProgressEvent) {
            mWorkProgressEvent(data1, data2);
        }
    }

protected:
    PluginEvent mWorkProgressEvent = nullptr;
    void *mWorkProgressData1 = nullptr;
    void *mWorkProgressData2 = nullptr;
};

python_callback.hpp

就所有不同的Python和C ++類型之間的映射缺失而言,該文件非常不完整。 我加了點( PyFloatdouble ,PyInt to詮釋, PyStringstd::string )這兩種方式給你一個藍圖如何將代碼與自己的映射擴展。

#pragma once
#include <Python.h>

#include <stdexcept>
#include <string>
#include <type_traits>

namespace internal {

// Convert C++ type to Python (add your favourite overloads)

inline PyObject *arg_to_python(double x) { return PyFloat_FromDouble(x); }
inline PyObject *arg_to_python(int v) { return PyInt_FromLong(v); }
inline PyObject *arg_to_python(std::string const &s) {
    return PyString_FromStringAndSize(s.c_str(), s.size());
}

// Convert Python type to C++ (add your favourite specializations)

template <typename T>
struct return_from_python {
    static T convert(PyObject *);
};

template <>
void return_from_python<void>::convert(PyObject *) {}

template <>
double return_from_python<double>::convert(PyObject *result) {
    if (!PyFloat_Check(result)) {
        throw std::invalid_argument("type is not PyFloat");
    }
    return PyFloat_AsDouble(result);
}

template <>
int return_from_python<int>::convert(PyObject *result) {
    if (!PyInt_Check(result)) {
        throw std::invalid_argument("type is not PyInt");
    }
    return PyInt_AsLong(result);
}

template <>
std::string return_from_python<std::string>::convert(PyObject *result) {
    char *buffer;
    Py_ssize_t len;
    if (PyString_AsStringAndSize(result, &buffer, &len) == -1) {
        throw std::invalid_argument("type is not PyString");
    }
    return std::string{buffer, static_cast<std::size_t>(len)};
}

// Scope Guard

template <typename F>
struct ScopeGuard_impl {
    F f;
    ScopeGuard_impl(F f) : f(std::move(f)) {}
    ~ScopeGuard_impl() { f(); }
};

template <typename F>
inline ScopeGuard_impl<F> ScopeGuard(F &&f) {
    return ScopeGuard_impl<F>{std::forward<F>(f)};
}

} // namespace internal

class PythonCallback {
    PyObject *callable = nullptr;

public:
    PythonCallback() = default;
    PythonCallback(PyObject *obj) : callable(obj) { Py_INCREF(obj); }
    ~PythonCallback() { Py_XDECREF(callable); }

    PythonCallback(PythonCallback const &other) : callable(other.callable) {
        Py_INCREF(callable);
    }

    PythonCallback &operator=(PythonCallback other) noexcept {
        if (this != &other) {
            std::swap(this->callable, other.callable);
        }
        return *this;
    }

    // Function caller
    template <typename ReturnType, typename... Args>
    ReturnType call(Args const &... args) {
        using internal::arg_to_python;
        using internal::return_from_python;
        using internal::ScopeGuard;

        PyGILState_STATE gil = PyGILState_Ensure();
        auto gil_ = ScopeGuard([&]() { PyGILState_Release(gil); });

        PyObject *const result = PyObject_CallFunctionObjArgs(
            callable, arg_to_python(args)..., nullptr);
        auto result_ = ScopeGuard([&]() { Py_XDECREF(result); });

        if (result == nullptr) {
            throw std::runtime_error("Executing Python callback failed!");
        }

        return return_from_python<ReturnType>::convert(result);
    }
};

我們可以使用一個希望打印“ Hello World!”的小腳本來測試上述設置。

test.py

from example import *

p = PluginWithEvents()

def callback(a, b, c):
    print("Hello World!")
    print(a,type(a))
    print(b,type(b))
    print(c,type(c))
    return 3.14

p.assignOnProgressEvent(callback)
p.workProgressEvent(None,None)

試試看

$ swig -c++ -python test.i
$ clang++ -Wall -Wextra -Wpedantic -std=c++11 -I /usr/include/python2.7/ -fPIC -shared test_wrap.cxx -o _example.so -lpython2.7
$ python test.py
Hello World!
('ABC', <type 'str'>)
(3.14, <type 'float'>)
(42L, <type 'long'>)
C++ reveived: 3.14

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM