Never defined structure - c

Is there any benefit in having never-defined structures in C ?
Example in SQLite source code :
/* struct sqlite3_stmt is never defined */
typedef struct sqlite3_stmt sqlite3_stmt;
And the object is manipulated like so :
typedef struct Vdbe Vdbe;
struct Vdbe {
/* lots of members */
};
int sqlite3_step(sqlite3_stmt *pStmt) {
Vdbe *v = (Vdbe*) pStmt;
/* do stuff with v... */
}
So why not just use a usual abstract type, with the actual structure privately defined in foo.c source and a public typedef in foo.h header ?

It is defined like this to hide the implementation detail of sqlite3_stmt from the user, thus avoiding the internal states from being messed around. See Opaque pointer.
(This also forces the user only to use the type as a pointer since the structure sqlite3_stmt itself has incomplete implementation.)
Edit: VDBE (virtual database engine) is just "a" back-end of the SQLite3 API. I believe the back-end is changeable, thus a sqlite3_stmt* is not necessarily a Vdbe*. Not exposing Vdbe* in the API because the back-end detail should not be exposed.

To clarify: What you're asking is why SQLite does the above instead of doing this:
Header file:
typedef struct sqlite3_stmt sqlite3_stmt;
C file:
struct sqlite3_stmt {
/* lots of members */
};
int sqlite3_step(sqlite3_stmt *pStmt) {
/* do stuff with pStmt... */
}
(This is the canonical form of the "opaque pointer" pattern linked to in KennyTM's answer.)
The only good reason I can think of why SQLite does what it does is the following:
The backend code, I'm speculating, came before the API and used the name Vdbe -- the name probably means something related to the implementation along the lines of "virtual database entry" (guessing wildly here).
When time came to create the API, someone realized that the parameter required by sqlite3_step was a Vdbe but that this was not exactly a name that would convey a lot to the user of the API. Hence, from the user's point of view, a Vdbe is referred to as an sqlite3_stmt.
The point here, then, is to differentiate between two views of the same item: The backend thinks in terms of Vdbes (whatever they are) because that's a name that makes sense in the context of the implementation. The API talks about sqlite3_stmts because that's a name that makes sense in the context of the interface.
Edit: As Amarghosh points out, why not just do this to achieve the same effect?
typedef struct Vdbe sqlite3_stmt;
KennyTM points out a good possible reason (please vote him up, I don't want to siphon off his rep here): VDBE is only one of several possible backends; the interface uses a "generic" sqlite3_stmt, and this is then cast to whatever the backend uses to implement it.

Related

How to access driver information from within the kernel?

I work with cpu management in big.LITTLE boards and the board on which I am developing on has some ina231 power sensors. Which I believe are handled by the ina2xx_driver (this would make sense to me). My knowledge of drivers is still in development so I am unsure about how I should get the information I need to my CPU module out of the driver/devices, in a way that wont make the Linux gods angry.
The board has 4 sensors which I believe are then stored in the struct i2c_driver in the linked list struct list_head clients. If I have understood this correctly, then my initial idea was to export a pointer to the driver
static struct i2c_driver ina2xx_driver = {
.driver = {
.name = "ina2xx",
},
.probe = ina2xx_probe,
.remove = ina2xx_remove,
.id_table = ina2xx_id,
};
+struct i2c_driver *ina2xx_driver_p = &ina2xx_driver;
+EXPORT_SYMBOL(ina2xx_driver_p);
to my module which could then step through the linked list of i2c clients allowing me to access individual device information by doing something like this
struct i2c_client *tmp
struct list_head *pos;
struct list_head *clients_head = &ina2xx_driver_p->clients;
list_for_each(pos, clients_head){
tmp = list_entry(pos, struct i2c_client, detected)
struct ina2xx_data *data = ina2xx_update_device(tmp.dev);
ina2xx_get_value(data, $(attribute));
}
I haven't actually tried this, it's just how I imagine one solution being after reading the header files. Given my lack of knowledge on the recommended practice I thought it would be best to ask before wasting a day or two trying to implement something that is destined to fail.
Is there a more standardized way that is used in the kernel to get device driver or device pointers to access information or way to get device information without reading it from files?
I hope my question makes sense and thanks.
The ina231 sensor on your board is most likely instantiated from DeviceTree. If that is the case, and your driver is also instantiated from DT, then it would be natural to store a phandle to ina231 sensor as a property in your DT node. Then you can use of_find_node_by_phandle() to get a struct device_node and then use of_find_i2c_device_by_node to turn it into struct i2c_client.
An alternative approach would be to use bus_find_device() with &i2c_bus_type as a first argument and using your custom match function. See the of_find_i2c_device_by_node implementation as an example on how this could be used.
Note that none of that will be pretty since you are planning on using driver private internal data which itself isn't a nice practice.

Using Lua FFI with complex types

Bit of a complicated use case... Trying to access a C++ Object inside of Lua FFI, via a C wrapper.
ffi.load("wrapper.so")
​
ffi.cdef[[
struct puppy;
typedef struct puppy puppy_t;
puppy_t * puppy_bark (const char *encoded);
]]
However every time I try to instantiate a puppy, it returns "size of C type is unknown or too large".
I've tried the following to get a puppy created...
pup = ffi.typeof("puppy_t")
pup.puppy_bark("some text")
Results in struct puppy has no member named puppy_bark
pup = ffi.new("struct puppy_t")
pup.puppy_bark("some text")
Returns undeclared or implicit tag
pup = ffi.new("struct puppy puppy_t")
pup.puppy_bark("some stringish thing")
Returns '<eof>' expected near puppy_t
Assuming that the C Wrapper correctly has a Puppy Struct, Type, and the requisite method, how do create an instance of or a pointer to a Puppy in order to make it bark?
Thanks in advance!
You ask "how do I create an instance of or a pointer to a puppy in order to make it bark" - but it's not possible to create an instance of something without having its definition, and it's not possible to create a pointer to something without having an instance of it, and puppies don't bark with your code anyway (but there is a global function puppy_bark that creates a new puppy?).
It looks like you can create a puppy by calling puppy_bark (in which case, what a horribly badly named function!), but I can't be sure of that without seeing the actual code behind puppy_bark.
Since I don't have a specific answer to a specific question, here are some things that are likely to help you:
ffi.new("puppy_t") doesn't work because the FFI needs to have the definition of struct puppy, not just a forward declaration, for exactly the same reason this won't work in C++:
struct puppy;
puppy *p = new puppy;
So, if you want to do this, you need to load the complete definition into the FFI. Note that LuaJIT's FFI only supports C code, not C++.
ffi.new("struct puppy_t") doesn't work because that's not a type that exists.
ffi.new("struct puppy puppy_t") don't work because that's not a valid type.
pup = ffi.typeof("puppy_t") pup.puppy_bark("some text") doesn't work because puppy_bark isn't a member of struct puppy (as the error message tells you).
It also seems like you're misunderstanding the purpose of ffi.typeof. According to the documentation, ffi.typeof returns a constructor for the given type, so that
local new_puppy = ffi.typeof("puppy_t")
local puppy = new_puppy(1, 2, 3, 4)
is the same as
local puppy = ffi.new("puppy_t", 1, 2, 3, 4)
If you want to call the global function puppy_bark, you can do that with ffi.C.puppy_bark("some text").

How to store a struct inside a struct in go?

I have two structure (New and DailyPrediction) with DailyPrediction structure as one of the entity of New structure:
type New struct {
Id string
DailyPrediction
}
type DailyPrediction struct {
Prediction string
}
I am unable to read (or) write the structure new in the datastore. It would be helpful if someone can help me on this.
It is unclear to me from your question what exactly you are doing with the struct, and in what way it is failing. However, while you are embedding the DailyPrediction struct in your new struct by not giving it a name, it still needs to be initialized. You can see details of how to do that here:
http://golang.org/doc/effective_go.html#embedding
For example, in order to initialize your New struct, you may use a line like this:
n := New{"foo", DailyPrediction{"bar"}}
Could that be what was missing?
Not supported by the appengine.
Just to update this post for future readers ... this info is OLD ... nested structs are now supported

Implementing Hierarchical State Machines in C

I'm a bit confused about how to implement my state machine.
I already know it's hierarchical since some states share the same action.
I determine what I need to do by these parameters:
Class (Values are: Base, Derived, Specific)
OpCode
Parameter 1 - optional
Parameter 2 - optional
My hierarchy is determined by the Class and the OpCode represents the action.
Derived can use the OpCodes of Base and Specific can use OpCodes of both Base and Derived.
The naive implementation is the following:
void (*const state_table [MAX_CLASSES][MAX_OPCODES]) (state *) {
{base_state1, base_state2, NULL, NULL},
{base_state1, base_state2, derived_state1, NULL},
{base_state1,base_state2, derived_state1, specific_state3},
};
void dispatch(state *s)
{
if (state_table[s->Class][s->OpCode] != NULL)
state_table[s->Class][s->OpCode](s);
}
This will turn unmaintainable really quick.
Is there another way to map the state to a superclass?
EDIT:
Further calcualtion leads me to think that I'll probably use most if not all OpCodes but I will not use all of the Classes available to me.
Another clarification:
Some OpCodes might be shared through multiple derived and base Classes.
For example:
I have a Class called Any
which is a Base class. It has the
OpCodes: STATE_ON, STATE_OFF, STATE_SET.
I have another Class called
MyGroup which is a Derived class. It has the OpCodes:
STATE_FLIP, STATE_FLOP.
The third Class is a Specific
class called ThingInMyGroup which
has the OpCode:
STATE_FLIP_FLOP_AND_FLOOP.
So a message with class Any is sent from the server, recieved in all clients and processed.
A message with class MyGroup is sent from the server, recieved in all clients and processed only on clients that belong to MyGroup, any OpCodes that are valid for the Any class are valid for the MyGroup class.
A message with class ThingInMyGroup is sent from the server, recieved in all clients and processed only on clients that belong to MyGroup and are a ThingInMyGroup*, any **OpCodes that are valid for the Any class and MyGroup class are valid for the ThingInMyGroup class.
After a message is received the client will ACK/NACK accordingly.
I prefer not to use switch cases or const arrays as they will become unmaintainable when they get bigger.
I need a flexible design that allows me:
To specify which OpCodes are available
for each Class.
To specify a superclass for each Class and through that specification to allow me to call the function pointer that is represented by the current OpCode.
There are several ways to deal with this. Here is one:
edit -- with general purpose hierarchy added
typedef unsigned op_code_type;
typedef void (*dispatch_type)(op_code_type);
typedef struct hierarchy_stack hierarchy_stack;
struct hierarchy_stack {
dispatch_type func;
hierarchy_stack *tail;
};
void dispatch(state *s, hierarchy_stack *stk) {
if (!stk) {
printf("this shouldn't have happened");
} else {
stk->func(s, stk->tail);
}
}
void Base(state *s, hierarchy_stack *stk ) {
switch (s->OpCode) {
case bstate1:
base_state1(s);
break;
case bstate2:
base_state(2);
break;
default:
dispatch(s, stk);
}
}
void Derived(state *s, hierarchy_stack *stk ) {
switch(s->opcode) {
case dstate1:
deriveds_state1(s);
break;
default:
dispatch(s, stk);
}
}
...
NOTE : All function calls are tail calls.
This localizes your "class"es a good bit so that if you decide that Derived needs 100 more methods/opcodes then you only have to edit methods and the enum (or whatever) that you use to define opcodes.
Another, more dynamic way, to deal with this would be to have a parent pointer within each "class" that pointed to the "class" that would handle anything that it could not handle.
The 2D table approach is fast and flexible (Derived could have a different handler than Base for opcode 0), but it grows fast.
I wrote a little tool that generates code similar to your naive implementation based on a mini-language. The language just specified the state-opcode-action relationships, all of the actions were just C functions conforming to a typedef.
It didn't handle the HSM aspect, but this would be relatively easy to add to a language.
I'd recommend taking this approach -- create a little language that gives you a clean way to describe the state machine, and then generate code based on that machine description. That way when you need to insert a new state a month from now, the whole thing isn't a tangled mess to edit.
Let me know if you want the code and I'll make sure it's still available somewhere.

Does this function IOHIDManagerRegisterDeviceMatchingCallback operate under the cocoa environment?

I am struggling to implement an HID control with a Mac : I cannot send the expected function as depicted here below:
IOHIDManagerRegisterDeviceMatchingCallback( gIOHIDManagerRef, Handle_DeviceMatchingCallback, NULL );
with : gIOHIDManagerRef -> the valid HID manager dedicated to this routine
Handle_DeviceMatchingCallback --> the routine that will be called back when the HID
device is attached to the USB port
NUUL --> not used here, contain data from the USB
The issue is that Handle_DeviceMatchingCallback must be a pointer to the routine, but how can I send a pointer ?
On the other hand, all the examples , from the Apple source, are based on C, not on cocoa.
Well, does that means that I must rework my program in C ??? Or is it possible to have fraction of the program in C under the cocoa environment?
Sorry for so "stupid" question queries, but, although I have some background in the field of electronic an programming, I am very newbees with cocoa.
Your comments will be very appreciated !
Michael
Objective-C is mostly a super-set of C. In order to combine C and Objective-C code, you simply compile your C code as if it were Objective-C code. The easiest way to do this in Xcode is to ensure the file in question has a .m extension.
To route handling back to the Objective-C world, you need a pointer to an Obj-C object. Many callback-based APIs allow you to provide a generic pointer (void *) that they then pass back to you when they callback. This argument has several common names:
context or ctx
refcon (for "reference constant")
userData
userInfo
If the callback API does not allow this, you'll need some uglier way to dispatch the callback to your object, such as a global pointer or a lookup table.
The API you're using does let you provide a context pointer. When it calls back to your code, it provides you with the pointer you used when you registered for the callback. Here is an example of registering the callback from an object of type MyObjCClass (see the -registerMatching method below) and then using the context pointer to route the callback back to the object that registered the callback for handling (see the Handle_DeviceMatchingCallback function's use of the context pointer).
/*! #file C-ObjC-Callbacks.m
* Demonstrates routing a C callback to an Obj-C object
* using the callback's context pointer.
*/
#import <Cocoa/Cocoa.h>
#import <IOKit/hid/IOHIDManager.h>
// Global HID manager reference.
IOHIDManagerRef gIOHIDManager;
// HID callback
void Handle_DeviceMatchingCallback(void *context,
IOReturn result,
void *sender,
IOHIDDeviceRef device);
#interface MyObjCClass : NSObject {
}
- (void)registerMatching;
- (void)handleMatchingDevice:(IOHIDDeviceRef)device
sender:(void *)sender
result:(IOReturn)result;
#end
#implementation MyObjCClass
- (void)registerMatching {
// Assume gIOHIDManager has already been created.
// Set up a device matching callback, providing a pointer to |self| as the context.
IOHIDManagerRegisterDeviceMatchingCallback(gIOHIDManager,
Handle_DeviceMatchingCallback,
(void *)self);
}
- (void)handleMatchingDevice:(IOHIDDeviceRef)device
sender:(void *)sender
result:(IOReturn)result {
// Do something...
}
#end
void
Handle_DeviceMatchingCallback(void *context,
IOReturn result,
void *sender,
IOHIDDeviceRef device); {
MyObjCClass *const myObject = (MyObjCClass *const)context;
[myObject handleMatchingDevice:device sender:sender result:result];
}
Handle_DeviceMatchingCallback must be a pointer to the routine, but how
can I send a pointer ?
If you want to pass in a function functionName, you can pass it as
&functionName.
On the other hand, all the examples , from the Apple source, are based on
C, not on cocoa. Well, does that means that I must rework my program in C
??? Or is it possible to have fraction of the program in C under the cocoa
environment?
You can mix C and Objective-C at will. As long as you pass it a function,
and not a method attached to an object, it should work.

Resources