-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclass_interface_mex.cpp
84 lines (64 loc) · 2.27 KB
/
class_interface_mex.cpp
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
#include "mex.h"
#include "class_handle.hpp"
// A set of utility functions are provided in class_handle.hpp
// in the namespace mexutils. These can be to convert between
// some matlab and std data types, and ease various tasks for
// the mex interface
using namespace mexutils;
// The class that we are interfacing to, this class would likely be
// defined elsewhere such as a library in ny real situation
class example
{
public:
example () { _x = 0; }
void train (int x)
{
_x = x;
}
int test ()
{
return _x;
}
private:
int _x;
};
// wrapper class to convert matlab arguments to appropriate arguments
// for wrapped class
class example_wrapper
{
public:
void train(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
std::vector<int> nallowed;
nallowed.push_back (1); // one argument must be supplied
// check the number of args supplied. We use an offset of 2, as the class
// interface always requires two arguements and we are only interested in the
// subsequent optional arguements
int noffsetargs = mxnarginchk (nrhs, nallowed, 2);
// get the input argument
double input = mxnthargscalar (nrhs, prhs, 1, 2);
// call the wrapped class's 'train' method
ex.train ( int(input) );
}
void test(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// return the value placed in _x
mxSetLHS (ex.test (), 1, nlhs, plhs);
}
private:
// instance of the wrapped c++ class
example ex;
};
// mexfunction defintion, all the interction with the class is done through
// this function
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// use the macros provided by class_handle.hpp to create the interface
// these macros assume the wrapper class can be constructed without arguments.
// Note that the instance of the wrapper class is declared with 'new' and
// created on the heap
BEGIN_MEX_CLASS_WRAPPER(example_wrapper)
REGISTER_CLASS_METHOD(example_wrapper,train)
REGISTER_CLASS_METHOD(example_wrapper,test)
END_MEX_CLASS_WRAPPER(example_wrapper)
}