I'm working on translating a C library to D and I was wondering what the best way to mimic the following C preprocessor macro in D is.
#define LV2_ATOM_SEQUENCE_FOREACH(seq, iter) \
for (LV2_Atom_Event* (iter) = lv2_atom_sequence_begin(&(seq).body); \
!lv2_atom_sequence_is_end(&(seq).body, (seq).atom.size, (iter)); \
(iter) = lv2_atom_sequence_next(iter))
Is this even possible to mimic with template programming or mixins in D?
An example of how the macro is used is
LV2_ATOM_SEQUENCE_FOREACH(self->control, event) {
do stuff with 'event'
...
}
I've tried writing a template which does something similar but I havent had much luck.
Any help or suggestions would be appreciated.
After a lot of trial and error I got it to work.
void LV2_ATOM_OBJECT_FOREACH(const (LV2_Atom_Object*) obj, void delegate(LV2_Atom_Property_Body* prop) iterDelegate)
{
for (LV2_Atom_Property_Body* iter = lv2_atom_object_begin(&obj.body);
!lv2_atom_object_is_end(&obj.body, obj.atom.size, iter);
iter = lv2_atom_object_next(iter))
{
iterDelegate(iter);
}
}
Then where the function is used
LV2_ATOM_OBJECT_FOREACH(object, delegate(LV2_Atom_Property_Body* prop)
{
...use prop here...
});
I'm still not sure that this is completely correct. The calling function is extern(C) If i try to make LV2_ATOM_OBJECT_FOREACH extern(C) as well I get the following error
function dplug.lv2.atomutil.LV2_ATOM_OBJECT_FOREACH(const(LV2_Atom_Object*) obj, extern (C) void delegate(LV2_Atom_Property_Body* prop) iterDelegate) is not callable using argument types (const(LV2_Atom_Object*), void delegate(LV2_Atom_Property_Body* prop) nothrow #system)
Thanks a lot to Adam for the suggestions on how to approach this problem.
Related
I have some ISR's and I do not really know how to documentate them by doxygen.
Do you have an idea?
Here an example. Is there any special code by doxygen to documentate this?
ISR(usartTimer_OVF_vect){
usartData.flag_send_data = TRUE;
}
Directly it is not possible as it is not valid C, but with workaround it could be possible.
#if defined(__DOXYGEN__)
void usartTimer_OVF_Vect(void)
#else
ISR(usartTimer_OVF_vect)
#endif
{
usartData.flag_send_data = TRUE;
}
In this case, doxygen will simply see a void function with usartTImer_OVF_Vect name without any parameters.
I was reading about the language vala and that it compiles to Ansi C code. However I also saw it supports generics like Java or Rust. Now my question is how this is compiled to C code? If I have a gerneric class or function, what kind of C code is generated to simulate the generic behavior?
Vala generics are based on gpointer and GType.
You can only specialize a Generic class with a pointer based type parameter.
class MyClass<T> {
public T val;
}
public static int main (string[] args) {
// This wouldn't compile!
// var il = new Gee.ArrayList<int> ();
var il = new Gee.ArrayList<int?> ();
var dl = new Gee.ArrayList<double?> ();
il.add (5);
dl.add (3.0);
var im = new MyClass<int?>();
im.val = 5;
var dm = new MyClass<double?>();
dm.val = 3.0;
var lm = new MyClass< Gee.List<int?> > ();
lm.val = il;
return 0;
}
You can check the generated code yourself with the -C parameter:
valac -C Main.vala --pkg gee-0.8
This will generate a main.c file. If you read it carefully you will see there is only one struct for MyClass (plus some additional helper structs that are needed for GObject based classes) that has a member gpointer val, it also has a GType t_type as well as a t_dup_func and a t_destroy_func.
struct _MyClass {
// ...
gpointer val;
};
struct _MyClassPrivate {
GType t_type;
GBoxedCopyFunc t_dup_func;
GDestroyNotify t_destroy_func;
};
To ensure the correct type is passed in GLib type checking is performed. This makes Vala generics type safe (partially at compile time and partially at runtime).
This is in contrast with C++ templates which are expanded at compile time. So it is closer to C# generics than to classic C++ templates.
I wrote "partially at compile time" because the Vala compiler is smart enough to omit the type check in the C code when it knows that the assignment will always be correct.
Also Vala generated C code is meant to be easily consumable for other programming languages that have GLib bindings (like C, Python, C++, GJS, etc.)
GCC has a nice feature about instrumentation which let you call a routine every time a function is called, or every time a function returns.
Now, I want to create my own system to make it portable to other compilers, and also to allow to instrumentalize the functions I want (which can vary in number of parameters), so I was thinking in two macro for both situations. I am thinking in making some kind of profile that it is activated only with a define clause.
#define FUNCT(t,function_name,...) \
(t) function_name(...) { \
(void) *func_pointer = &(function_name); \
start_data(func_pointer, myclock());
#define RETURN(x) {stop_data(func_pointer, myclock()); return (x);}
FUNCT(BOOL, LMP, const int prof, const int nmo))
if (nmo <= 5 ||
prof > (prof_l / 3)) {
.... do long operations....
RETURN(FALSE);
}
... do more....
RETURN(TRUE);
}
but I can’t get it to work. Can someone help me with this? or is this a difficult task to accomplish?
Other alternative that comes to my mind is let the function declare without a macro, and if it is anyway to know the function pointer without knowing its name, something like in VB when you call a Form with Me, with it is a generic alias. is it possible?
Use gcc -E to debug your macros. Using the code you posted:
$ gcc -E t.c
# ... skip stuff ....
(BOOL) LMP(...) { (void) *func_pointer = &(LMP);
start_data(func_pointer, myclock());)
if (nmo <= 5 ||
prof > (prof_l / 3)) {
.... do long operations....
{stop_data(func_pointer, myclock()); return (FALSE);};
}
... do more....
{stop_data(func_pointer, myclock()); return (TRUE);};
}
(I added some whitespace to make it readable.)
You can see two problems immediately: function arguments didn't get expanded as you thought they would, and there's an extra ) from somewhere.
To get the expanded variadic arguments, use __VA_ARGS__, not .... The stray ) is at the call site.
So:
#define FUNCT(t,function_name,...) \
(t) function_name(__VA_ARGS__) { \
(void) *func_pointer = &(function_name); \
start_data(func_pointer, myclock());
#define RETURN(x) {stop_data(func_pointer, myclock()); return (x);}
FUNCT(BOOL, LMP, const int prof, const int nmo)
if (nmo <= 5 ||
prof > (prof_l / 3)) {
.... do long operations....
RETURN(FALSE);
}
... do more....
RETURN(TRUE);
}
As to whether this is worth trying (variadic macros came with C99, not all compilers implement that standard, and support might vary from compiler to compiler), I'm not certain. You are probably better off using each compiler's native profiling tools - you'll get better results with hopefully less overhead.
It is much easier to instrument your functions at the calling side instead of the function side. A macro can have the same name as a function. Declare your replacement function somewhere
double myfunc_wrapper(int someArg) {
double ret = 0;
// do something before
...
// now call it
ret = (myfunc)(someArg);
// Then do something after
....
return ret;
}
Just to be sure put the () arround the call itself to be sure that always a function is called and not a macro.
And then "overload" your function with a macro
#define myfunc(...) mfunc_wrapper(__VA_ARGS__)
with that idea you can replace your function on the fly in the compilation units that interes you.
in addition to Mat, there is a ergonimical problem with using #define RETURN(x) {...}:
if (test)
RETURN (TRUE);
else
RETURN (FALSE);
will evaluate to
if (test)
{...}
; // <syntactical error
else
{...}
;
We use a simple object model for our low level networking code at work where struct pointers are passed around to functions which are pretending to be methods. I've inherited most of this code which was written by consultants with passable C/C++ experience at best and I've spent many late nights trying to refactor code into something that would resemble a reasonable structure.
Now I would like to bring the code under unit testing but considering the object model we have chosen I have no idea how to mock objects. See the example below:
Sample header (foo.h):
#ifndef FOO_H_
#define FOO_H_
typedef struct Foo_s* Foo;
Foo foo_create(TcpSocket tcp_socket);
void foo_destroy(Foo foo);
int foo_transmit_command(Foo foo, enum Command command);
#endif /* FOO_H_ */
Sample source (foo.c):
struct Foo_s {
TcpSocket tcp_socket;
};
Foo foo_create(TcpSocket tcp_socket)
{
Foo foo = NULL;
assert(tcp_socket != NULL);
foo = malloc(sizeof(struct Foo_s));
if (foo == NULL) {
goto fail;
}
memset(foo, 0UL, sizeof(struct Foo_s));
foo->tcp_socket = tcp_socket;
return foo;
fail:
foo_destroy(foo);
return NULL;
}
void foo_destroy(Foo foo)
{
if (foo != NULL) {
tcp_socket_destroy(foo->tcp_socket);
memset(foo, 0UL, sizeof(struct Foo_s));
free(foo);
}
}
int foo_transmit_command(Foo foo, enum Command command)
{
size_t len = 0;
struct FooCommandPacket foo_command_packet = {0};
assert(foo != NULL);
assert((Command_MIN <= command) && (command <= Command_MAX));
/* Serialize command into foo_command_packet struct */
...
len = tcp_socket_send(foo->tcp_socket, &foo_command_packet, sizeof(foo_command_packet));
if (len < sizeof(foo_command_packet)) {
return -1;
}
return 0;
}
In the example above I would like to mock the TcpSocket object so that I can bring "foo_transmit_command" under unit testing but I'm not sure how to go about this without inheritance. I don't really want to redesign the code to use vtables unless I really have to. Maybe there is a better approach to this than mocking?
My testing experience comes mainly from C++ and I'm a bit afraid that I might have painted myself into a corner here. I would highly appreciate any recommendations from more experienced testers.
Edit:
Like Richard Quirk pointed out it is really the call to "tcp_socket_send" that I want to override and I would prefer to do it without removing the real tcp_socket_send symbol from the library when linking the test since it is called by other tests in the same binary.
I'm starting to think that there is no obvious solution to this problem..
You can use macro to redefine tcp_socket_send to tcp_socket_send_moc and link with real tcp_socket_send and dummy implementation for tcp_socket_send_moc.
you will need to carefully select the proper place for :
#define tcp_socket_send tcp_socket_send_moc
Have a look at TestDept:
http://code.google.com/p/test-dept/
It is an open source project that aims at providing possiblity to have alternative implementations, e.g. stubs, of functions and being able to change in run-time which implementation of said function to use.
It is all accomplished by mangling object files which is very nicely described on the home page of the project.
Alternatively, you can use TestApe TestApe Unit testing for embedded software - It can do it, but note it is C only.
It would go like this -->
int mock_foo_transmit_command(Foo foo, enum Command command) {
VALIDATE(foo, a);
VALIDATE(command, b);
}
void test(void) {
EXPECT_VALIDATE(foo_transmit_command, mock_foo_transmit_command);
foo_transmit_command(a, b);
}
Not sure what you want to achieve.
You can add all foo_* functions as function pointer members to struct Foo_s but you still need to explicitly pass pointer to your object as there is no implicit this in C. But it will give you encapsulation and polymorphism.
What OS are you using? I believe you could do an override with LD_PRELOAD on GNU/Linux: This slide looks useful.
Use Macro to refine tcp_socket_send is good. But the mock only returns one behavior. Or you need implement some variable in the mock function and setup it differently before each test case.
Another way is to change tcp_socket_send to function point. And points it to different mock function for different test case.
To add to Ilya's answer. You can do this.
#define tcp_socket_send tcp_socket_send_moc
#include "your_source_code.c"
int tcp_socket_send_moc(...)
{ ... }
I use the technique of including the source file into the unit testing module to minimize modifications in the source file when creating unit tests.
Hello. I am trying to make a fully thread-safe initialization function for my library and I couldn't easily find an alternative to pthread_once, which should solve the problem very easily. I've come to this code:
void libInit (void)
{
#ifdef WIN32
static volatile int initialized = 0;
static HANDLE mtx;
if (!initialized)
{
if (!mtx)
{
HANDLE mymtx;
mymtx = CreateMutex(NULL, 0, NULL);
if (InterlockedCompareExchangePointer(&mtx, mymtx, NULL) != NULL)
CloseHandle(mymtx);
}
WaitForSingleObject(mtx);
if (!initialized)
{
libInitInternal();
initialized = 1;
}
ReleaseMutex(mtx);
}
#else
static pthread_once_t initialized = PTHREAD_ONCE_INIT;
pthread_once(&initialized, libInitInternal);
#endif
}
The libInitInternal() call leads to a thread-unsafe function, that initializes the library.
I would like to hear any suggestions on what I could be doing wrong or whether you know about a better solution.
I think you want to use the One-Time Initialization functionality. In synchronous mode, all threads block until the first thread to call it completes. Seems analogous to pthread_once().
There is sample code here.
So in your case, you would say:
BOOL CALLBACK CallLibInitInternal(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *lpContex) {
libInitInternal();
return TRUE;
}
void libInit() {
#ifdef WIN32
static INIT_ONCE s_init_once;
InitOnceExecuteOnce(&s_init_once, CallLibInitInternal, NULL, NULL);
#else
...
#endif
}
You might want to check what pthreads-win32 does in its pthread_once() implementaion. or just use that, if that proves to be easier.
After looking at the following source code for pthread_once() (from here), It looks like you're on the right track.
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
{
/* Check first for speed */
if (once_control->state == PTHREAD_NEEDS_INIT) {
pthread_mutex_lock(&(once_control->mutex));
if (once_control->state == PTHREAD_NEEDS_INIT) {
init_routine();
once_control->state = PTHREAD_DONE_INIT;
}
pthread_mutex_unlock(&(once_control->mutex));
}
return(OK);
}
btw, I'll be using pthread_once() to replace some rather convoluted functions in my code.
When using GCC or clang, you can use constructor and destructor attributes. These work for both shared and static libraries, and execute code before and after main is run, respectively. Additionally, you can specify multiple constructor and destructor functions. Much cleaner than the singleton approach, and doesn't require you to remember to call libInit() from your main().
static void __attribute__((constructor))
your_lib_init(void)
{
fprintf(stderr, "library init\n");
}
static void __attribute__((destructor))
vensim_ctx_destroy(void)
{
fprintf(stderr, "library destroy\n");
}
I would check out this article. It is a solution for C++ singletons, but I believe you can use the solution for your code as well: http://www.ddj.com/cpp/199203083?pgno=1
Sadly the listing for the QLock itself is missing, it looks as if they are trying to sell the CD, but there appears to be enough description of it to write one yourself.