реклама на сайте
подробности

 
 
> Массив меток на C, возможно ли сделать?
ViKo
сообщение Jun 3 2012, 16:31
Сообщение #1


Универсальный солдатик
******

Группа: Модераторы
Сообщений: 8 634
Регистрация: 1-11-05
Из: Минск
Пользователь №: 10 362



Можно сделать массив указателей на низкоуровневые функции. А в функции верхнего уровня по индексу вызывать один уз указателей. Но отъедаются ресурсы на вызов низкоуровневой функции и возврат из нее. Как бы сделать это в виде массива из меток на низкоуровневые части, которыми набита одна функция верхнего уровня?
Можно, конечно, в виде switch - case... Наверное, зря я голову ломаю.
Go to the top of the page
 
+Quote Post
 
Start new topic
Ответов
maksimp
сообщение Jun 3 2012, 16:38
Сообщение #2


Местный
***

Группа: Участник
Сообщений: 313
Регистрация: 2-07-11
Пользователь №: 66 023



Цитата(ViKo @ Jun 3 2012, 20:31) *
Как бы сделать это в виде массива из меток

На стандартном Си нельзя. Но GCC имеет такую возможнось:
http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
Цитата
6.3 Labels as Values

You can get the address of a label defined in the current function (or a containing function) with the unary operator `&&'. The value has type void *. This value is a constant and can be used wherever a constant of that type is valid. For example:

void *ptr;
/* ... */
ptr = &&foo;

To use these values, you need to be able to jump to one. This is done with the computed goto statement1, goto *exp;. For example,

goto *ptr;

Any expression of type void * is allowed.

One way of using these constants is in initializing a static array that will serve as a jump table:

static void *array[] = { &&foo, &&bar, &&hack };

Then you can select a label with indexing, like this:

goto *array[i];

Note that this does not check whether the subscript is in bounds—array indexing in C never does that.

Such an array of label values serves a purpose much like that of the switch statement. The switch statement is cleaner, so use that rather than an array unless the problem does not fit a switch statement very well.

Another use of label values is in an interpreter for threaded code. The labels within the interpreter function can be stored in the threaded code for super-fast dispatching.

You may not use this mechanism to jump to code in a different function. If you do that, totally unpredictable things will happen. The best way to avoid this is to store the label address only in automatic variables and never pass it as an argument.

An alternate way to write the above example is

static const int array[] = { &&foo - &&foo, &&bar - &&foo,
&&hack - &&foo };
goto *(&&foo + array[i]);

This is more friendly to code living in shared libraries, as it reduces the number of dynamic relocations that are needed, and by consequence, allows the data to be read-only.

The &&foo expressions for the same label might have different values if the containing function is inlined or cloned. If a program relies on them being always the same, __attribute__((__noinline__,__noclone__)) should be used to prevent inlining and cloning. If &&foo is used in a static variable initializer, inlining and cloning is forbidden.
Go to the top of the page
 
+Quote Post



Reply to this topicStart new topic
1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0

 


RSS Текстовая версия Сейчас: 18th August 2025 - 07:24
Рейтинг@Mail.ru


Страница сгенерированна за 0.02282 секунд с 7
ELECTRONIX ©2004-2016