How can I mock ioctl in D? - linux-device-driver

I want to write a D class which wraps a I2C device driver (/dev interface -> I2C device files/character device files). To break dependencies on the HW during implementation I would like to mock ioctl(). How can I do this most easily?

writeln("hey ioctl, your mother is a hamster and your father smells of elderberries!");
nah I'm just kidding.
What I'd do is prolly write a fake ioctl function that looks the same and use the import and version to trick it:
import core.sys.posix.sys.ioctl;
version(unittest)
int ioctl(int d, int request, ...) {
import std.stdio;
writeln("its a fake!");
return 0;
}
void main() {
ioctl(0, 0);
}
Compiling+running that with and without unittests will yield a different result. Your local function can be called instead of the real one.

Related

How to control argument passing policy in pybind11 wrapping of std::function?

I have a class in c++ that I'm wrapping into python with pybind11. That class has a std::function, and I'd like to control how the arguments to that function are dealt with (like return value policies). I just can't find the syntax or examples to do this...
class N {
public:
using CallbackType = std::function<void(const OtherClass*)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
OtherClass * o = new OtherClass();
callback(o);
}
}
wrapped with
py::class_<OtherClass>(...standard stuff...);
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(),
py::arg("callback"));
I all works: I can do this in python:
def callback(o):
dosomethingwith(o)
k = N(callback)
, but I'd like to be able to control what happens when callback(o); is called - whether python then will take ownership of the wrapped o variable or not, basically.
I put a printout in the destructor of OtherClass, and as far as I can tell, it never gets called.
OK, I think I figured it out:
Instead of std::function, use a pybind11::function:
using CallbackType = pybind11::function
and then
void doit(const OtherClass &input) {
if (<I want to copy it>) {
callback(pybind11::cast(input, pybind11::return_value_policy::copy));
} else {
callback(pybind11::cast(input, pybind11::return_value_policy::reference));
}
}
I see nothing in pybind11/functional that allows you to change the ownership of the parameters at the point of call, as the struct func_wrapper used is function local, so can not be specialized. You could provide another wrapper yourself, but in the code you can't know whether the callback is a Python function or a bound C++ function (well, technically you can if that bound C++ function is bound by pybind11, but you can't know in general). If the function is C++, then changing Python ownership in the wrapper would be the wrong thing to do, as the temporary proxy may destroy the object even as its payload is stored by the C++ callback.
Do you have control over the implementation of class N? The reason is that by using std::shared_ptr all your ownership problems will automagically evaporate, regardless of whether the callback function is C++ or Python and whether it stores the argument or not. Would work like so, expanding on your example above:
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
namespace py = pybind11;
class OtherClass {};
class N {
public:
using CallbackType = std::function<void(const std::shared_ptr<OtherClass>&)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
auto o = std::make_shared<OtherClass>();
callback(o);
}
};
PYBIND11_MODULE(example, m) {
py::class_<OtherClass, std::shared_ptr<OtherClass>>(m, "OtherClass");
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(), py::arg("callback"))
.def("doit", &N::doit);
}

How to avoid interface method implementations that needs a pointer receiver?

Consider the following example: http://play.golang.org/p/eAot_sVwND
package main
import "fmt"
type Incrementor interface {
Increment()
}
type Counter struct {
i int
Incrementor
}
func (c *Counter) Increment(){
c.i++
}
func main() {
var c Incrementor
c = &Counter{}
c.Increment()
fmt.Println(c)
}
Unfortunatelly I need to c = &Counter{} because Counter.Increment() implementation has a pointer receiver otherwise c.Increment() calls won't be able to modify c.x property:
func (c Counter) Increment(){
c.i++ // no errors, but now we increment c.x having a copy of c as context
}
How to make original implementation works without & on c = &Counter{}? In other words, how to avoid the need for the pointer receiver on C.Increment implementation at all?
This is just a nit, but I think that maybe a pointer is not necessary to do that in Go.
This is just a nit, but I think that maybe a pointer is not necessary to do that in Go.
Considering that Go uses to pass everything by value, a pointer receiver is the natural way to achieve what you want.
This is supported by the Go FAQ:
First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer.
You would find a similar conclusion in "Things I Wish Someone Had Told Me About Golang: pointers"
You could consider defining an NewCounter function that encapsulates the initialization of your type (or some 3rd party) and returns a *Counter. Usage could look something like this:
func main() {
c := NewCounter()
c.Increment()
fmt.Println(c)
}

Python Garbage Collection causes SegFault when destructing a C++ object

I have an in-house C++ library that I've successfully exposed to Python using Boost.Python. It accepts a user-created Python object and then uses some methods within that object to perform certain tasks, and it works quite well for the most part.
The Python use of the library looks like:
class Foo(object):
def __init__(self, args):
"""create an instance of this class with instance-specific attributes"""
def Bar1(self, a, b, c):
"""do something with the given integers a, b and c"""
return a + (b*c)
def Bar2(self, a, b, c):
"""do something else with the given integers a, b and c"""
print (a*b) + c
import mylib
cheese = mylib.Wine()
qux = Foo()
cheese.setup(qux)
cheese.do_something(1)
cheese.do_something(2)
The "Wine" object in C++ looks like:
#include <boost/python.h>
#include <Python.h>
class Wine {
public:
Wine() {};
~Wine() {};
void setup(boost::python::object baz) {
baz_ = baz;
};
static void do_something(boost::python::object pyreq) {
int request = boost::python::extract<int>(pyreq);
int a = 1;
int b = 2;
int c = 3;
if (request == 1) {
int d = boost::python::extract<int>(baz_.attr("Bar1")(a, b, c));
};
else if (request == 2) {
baz_.attr("Bar2")(a, b, c);
};
};
private:
static boost::python::object baz_;
};
BOOST_PYTHON_MODULE(mylib)
{
using namespace boost::python;
class_<Wine>("Wine")
.def("do_something", &Wine::do_something)
.staticmethod("do_something")
.def("setup", &Wine::setup)
;
};
The problem is that, after successfully executing all of the tasks, the program terminates with a SegFault. This isn't really a huge deal because the code that I need to execute still executes, and the tasks that I need to perform are all performed. The SegFault only occurs on the destruction of this C++ "Wine" object. Still, it's an inelegant outcome and I'd like to fix the problem.
What I could gather from an online search implied that this is a problem with improper declaration of ownership to Python. The end result is that the C++ destructor gets called twice, and the second call causes a SegFault.
Unfortunately I haven't been able to remedy the problem so far. Available documentation only covers the basics and I haven't been able to replicate some success others have had using boost smart pointers and some fancy declaration/destruction tricks in C++ with it. Any guidance would be much appreciated.
The problem is that the static Wine::baz_ object is being destroyed during static/global destruction. This is after the Python runtime has been finalized, but since boost::python::object uses the Python C-API, its destruction requires a valid Python runtime (though possible not if the object refers to None.) By arranging for baz_ to be destroyed before Python finalization, you should be able to avoid the segfault. The cleanest approach overall might be to make baz_ a non-static member variable.

Call function in main program from a library in Arduino

I've just started making libraries in Arduino. I've made a library named inSerialCmd. I want to call a function named delegate() that is defined in the main program file, stackedcontrol.ino, after the inSerialCmd library is included.
When I try to compile, one error is thrown:
...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp: In member function
'void inSerialCmd::serialListen()':
...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:32: error:
'delegate' has not been declared
After doing a bit of searching, it seemed that adding the scope resolution operator might do the trick. So I added the "::" before delegate(), now "::delegate()", but the same error is thrown.
Now I'm stumped.
You cannot and should not directly call a function in a program from a library. Keep in mind a key aspect that makes a library into a library:
A library does not depend on the specific application. A library can be fully compiled and packaged into the .a file without the existence of a program.
So there is a one way dependency, a program depends on a library. This at first glance may seem to prevent you from achieving what you want. You can achieve the functionality you are asking about through what is sometimes referred to as a callback. The main program would provide to the library at runtime a pointer to the function to execute.
// in program somwehere
int myDelegate(int a, int b);
// you set this to the library
setDelegate( myDelegate );
You see this in the arduino if you look at how interrupt handlers are installed. This same concept exists in many environments - event listeners, action adapters - all with the same goal of allowing a program to define the specific action that a library cannot know.
The library would store and call the function via the function pointer. Here is a rough sketch of what this looks like:
// in the main program
int someAction(int t1, int t2) {
return 1;
}
/* in library
this is the delegate function pointer
a function that takes two int's and returns an int */
int (*fpAction)(int, int) = 0;
/* in library
this is how an application registers its action */
void setDelegate( int (*fp)(int,int) ) {
fpAction = fp;
}
/* in libary
this is how the library can safely execute the action */
int doAction(int t1, int t2) {
int r;
if( 0 != fpAction ) {
r = (*fpAction)(t1,t2);
}
else {
// some error or default action here
r = 0;
}
return r;
}
/* in program
The main program installs its delegate, likely in setup() */
void setup () {
...
setDelegate(someAction);
...

Using classes with the Arduino

I'm trying to use class objects with the Arduino, but I keep running into problems. All I want to do is declare a class and create an object of that class. What would an example be?
On Arduino 1.0, this compiles just fine:
class A
{
public:
int x;
virtual void f() { x=1; }
};
class B : public A
{
public:
int y;
virtual void f() { x=2; }
};
A *a;
B *b;
const int TEST_PIN = 10;
void setup()
{
a=new A();
b=new B();
pinMode(TEST_PIN,OUTPUT);
}
void loop()
{
a->f();
b->f();
digitalWrite(TEST_PIN,(a->x == b->x) ? HIGH : LOW);
}
There is an excellent tutorial on how to create a library for the Arduino platform. A library is basically a class, so it should show you how its all done.
On Arduino you can use classes, but there are a few restrictions:
No new and delete keywords
No exceptions
No libstdc++, hence no standard functions, templates or classes
You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE.
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:
By default, the Arduino IDE and
libraries does not use the operator
new and operator delete. It does
support malloc() and free(). So the
solution is to implement new and
delete operators for yourself, to use
these functions.
Code:
#include <stdlib.h> // for malloc and free
void* operator new(size_t size) { return malloc(size); }
void operator delete(void* ptr) { free(ptr); }
This let's you create objects, e.g.
C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory
Regards,
tamberg
I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:
class AMLed
{
private:
uint8_t _ledPin;
long _turnOffTime;
public:
AMLed(uint8_t pin);
void setOn();
void setOff();
// Turn the led on for a given amount of time (relies
// on a call to check() in the main loop()).
void setOnForTime(int millis);
void check();
};
And here is the main source
AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
pinMode(_ledPin, OUTPUT);
}
void AMLed::setOn()
{
digitalWrite(_ledPin, HIGH);
}
void AMLed::setOff()
{
digitalWrite(_ledPin, LOW);
}
void AMLed::setOnForTime(int p_millis)
{
_turnOffTime = millis() + p_millis;
setOn();
}
void AMLed::check()
{
if (_turnOffTime != 0 && (millis() > _turnOffTime))
{
_turnOffTime = 0;
setOff();
}
}
It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html
To use, I simply do something like this in the .pde file:
#include "AM_Led.h"
#define TIME_LED 12 // The port for the LED
AMLed test(TIME_LED);
My Webduino library is all based on a C++ class that implements a web server on top of the Arduino Ethernet shield. I defined the whole class in a .h file that any Arduino code can #include. Feel free to look at the code to see how I do it... I ended up just defining it all inline because there's no real reason to separately compile objects with the Arduino IDE.
Can you provide an example of what did not work? As you likely know, the Wiring language is based on C/C++, however, not all of C++ is supported.
Whether you are allowed to create classes in the Wiring IDE, I'm not sure (my first Arduino is in the mail right now). I do know that if you wrote a C++ class, compiled it using AVR-GCC, then loaded it on your Arduino using AVRDUDE, it would work.