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 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
# mode: run
# tag: cpp, cpp11
from libcpp.functional cimport function
cimport cpp_function_lib
def test_simple_function():
'''
>>> test_simple_function()
6.0
'''
return cpp_function_lib.add_one(2.0, 3)
def test_AddAnotherFunctor(n):
'''
>>> test_AddAnotherFunctor(5.0)
10.0
'''
return cpp_function_lib.AddAnotherFunctor(5.0).call(2.0, 3)
cdef class FunctionKeeper:
"""
>>> fk = FunctionKeeper('add_one')
>>> fk(2.0, 3)
6.0
>>> fk = FunctionKeeper('add_two')
>>> fk(2.0, 3)
7.0
>>> fk = FunctionKeeper('AddAnotherFunctor5')
>>> fk(2.0, 3)
10.0
>>> fk = FunctionKeeper('default')
>>> bool(fk)
False
>>> fk(2.0, 3)
Traceback (most recent call last):
...
RuntimeError: Trying to call undefined function!
>>> fk.set_function('AddAnotherFunctor5')
>>> fk(2.0, 3)
10.0
>>> bool(fk)
True
>>> fk.set_function('NULL')
>>> bool(fk)
False
"""
cdef cpp_function_lib.FunctionKeeper* function_keeper
cdef function[double(double, int) noexcept]* _get_function_ptr_from_name(self, function_name):
cdef function[double(double, int) noexcept] *f
if function_name == 'add_one':
f = new function[double(double, int) noexcept](cpp_function_lib.add_one)
elif function_name == 'add_two':
f = new function[double(double, int) noexcept](cpp_function_lib.add_two)
elif function_name == 'AddAnotherFunctor5':
f = new function[double(double, int) noexcept]()
f[0] = cpp_function_lib.AddAnotherFunctor(5.0)
elif function_name == 'NULL':
f = new function[double(double, int) noexcept](NULL)
elif function_name == 'default':
f = new function[double(double, int) noexcept]()
return f
def __cinit__(self, function_name):
cdef function[double(double, int) noexcept] *f = self._get_function_ptr_from_name(function_name)
self.function_keeper = new cpp_function_lib.FunctionKeeper(f[0])
del f
def __dealloc__(self):
del self.function_keeper
def __call__(self, a, b):
return self.function_keeper.call_function(a, b)
def __bool__(self):
return <bint> self.function_keeper.get_function()
def set_function(self, function_name):
cdef function[double(double, int) noexcept] *f = self._get_function_ptr_from_name(function_name)
self.function_keeper.set_function(f[0])
del f
|