aboutsummaryrefslogtreecommitdiffstats
path: root/include/qdotnetfunction.h
blob: 531a795540b5a571d1fe482136b0476e0d028adc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/***************************************************************************************************
 Copyright (C) 2023 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

#pragma once

#include "qdotnetmarshal.h"

#ifdef Q_OS_WINDOWS
#   define QDOTNETFUNCTION_CALLTYPE __stdcall
#else
#   define QDOTNETFUNCTION_CALLTYPE
#endif

template<typename T, typename... TArg>
class QDotNetFunction
{
public:
    QDotNetFunction(void *funcPtr = nullptr)
        : funcPtr(reinterpret_cast<Delegate>(funcPtr))
    {}

    QDotNetFunction(const QDotNetFunction &cpySrc)
        : funcPtr(cpySrc.funcPtr)
    {}

    QDotNetFunction &operator=(const QDotNetFunction &cpySrc)
    {
        this->funcPtr = cpySrc.funcPtr;
        return *this;
    }

    void *ptr() const { return reinterpret_cast<void *>(funcPtr); }
    bool isValid() const { return funcPtr != nullptr; }

    typename QDotNetInbound<T>::TargetType operator()(
        typename QDotNetOutbound<TArg>::SourceType... arg) const
    {
        if (!isValid())
            return QDotNetNull<T>::value();
        return QDotNetInbound<T>::convert(funcPtr(QDotNetOutbound<TArg>::convert(arg)...));
    }

private:
    using Delegate = typename QDotNetInbound<T>::InboundType(QDOTNETFUNCTION_CALLTYPE *)(
        typename QDotNetOutbound<TArg>::OutboundType...);
    Delegate funcPtr = nullptr;
};

template<typename... TArg>
class QDotNetFunction<void, TArg...>
{
public:
    QDotNetFunction(void *funcPtr = nullptr)
        : funcPtr(reinterpret_cast<Delegate>(funcPtr))
    {}

    void *ptr() const { return reinterpret_cast<void *>(funcPtr); }
    bool isValid() const { return funcPtr != nullptr; }

    void operator()(typename QDotNetOutbound<TArg>::SourceType... arg) const
    {
        if (isValid())
            funcPtr(QDotNetOutbound<TArg>::convert(arg)...);
    }

private:
    using Delegate = void(QDOTNETFUNCTION_CALLTYPE *)(
        typename QDotNetOutbound<TArg>::OutboundType...);
    Delegate funcPtr = nullptr;
};