Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Основная";
Текущий архив: 2005.10.30;
Скачать: [xml.tar.bz2];

Вниз

Получение и использование адреса метода.   Найти похожие ветки 

 
Kostafey ©   (2005-10-06 23:19) [0]

Прошу помощи у уважаемых мастеров !

Итак, есть "схема" функции:

 TFunc = function (x:real):real;
 PFunc = ^TFunc;

Подобного рода функция описана как метод класса:
function TFunctions.my_f(x:real):real;

Хотелось бы знать как правильно сделать 2 вещи:
1) Получить адрес этого метода, навроде

var FuncPointer:PFunc;
    Functions:TFunctions;
...
 FuncPointer:=Functions.@my_f; //Не верно !

2) Использовать полученный адрес "по назначению":
var f,x:real;
...
f := FuncPointer^ (x); //Синтаксис-то верен, но приложение
                              //аварийно завешается


 
Eraser ©   (2005-10-06 23:25) [1]


> Kostafey ©   (06.10.05 23:19)


> Подобного рода функция описана как метод класса:

настараживает данное высказываение.

> 1) Получить адрес этого метода, навроде

Так всё таки метода или функции ?
Если var FuncPointer:PFunc;
то FuncPointer и есть указатель.

По-моему следует пересмотреть архитектуру.


 
Kostafey ©   (2005-10-06 23:31) [2]

> Так всё таки метода или функции ?

Да это именно метод класса.

> то FuncPointer и есть указатель.

А кто спорит ? Ему-и нужно присвоить адрес метода !


 
Eraser ©   (2005-10-06 23:36) [3]


> Kostafey ©   (06.10.05 23:31) [2]

Тогда определение TFunc = function (x:real):real; не верно.
Это объявлена вункция, а не метод.
Нужно так TFunc = function (x:real):real of object;


 
Eraser ©   (2005-10-06 23:37) [4]


> Kostafey ©   (06.10.05 23:19)

А в чём вообще трудности ?


 
Kostafey ©   (2005-10-06 23:54) [5]


> Это объявлена вункция, а не метод.
> Нужно так TFunc = function (x:real):real of object;

Так, благодарю, исправил.

> А в чём вообще трудности ?

А как адрес-то его получить:
FuncPointer:=Functions.@my_f; - никак не хочет работать


 
Eraser ©   (2005-10-07 00:04) [6]


> Kostafey ©   (06.10.05 23:54) [5]

1. Почитайте в стандартной справке статью, которая в Index обозначена как method pointers.
2.
>  TFunc = function (x:real):real;
>  PFunc = ^TFunc;

так лучше не делать... см. 1. там всё очень доходчиво расписано, с примерами.
Всё на самом деле гораздо проще ;-)


 
Kostafey ©   (2005-10-07 00:14) [7]

ёпрст !
Нет такого раздела в справке :(
Ссылка на ее есть, а самой статьи нет.

Если это вас не очень затруднит: Kostafey@Rambler.ru
или если можно на форуме в 2- х словах - главное синтаксис команды


 
Eraser ©   (2005-10-07 00:18) [8]


> Kostafey ©   (07.10.05 00:14) [7]

Procedural types allow you to treat procedures and functions as values that can be assigned to variables or passed to other procedures and functions. For example, suppose you define a function called Calc that takes two integer parameters and returns an integer:

function Calc(X,Y: Integer): Integer;

You can assign the Calc function to the variable F:

var F: function(X,Y: Integer): Integer;
F := Calc;


If you take any procedure or function heading and remove the identifier after the word procedure or function, what"s left is the name of a procedural type. You can use such type names directly in variable declarations (as in the previous example) or to declare new types:

type
 TIntegerFunction = function: Integer;
 TProcedure = procedure;
 TStrProc = procedure(const S: string);
 TMathFunc = function(X: Double): Double;
var
 F: TIntegerFunction;             { F is a parameterless function that returns an integer }
 Proc: TProcedure;                { Proc is a parameterless procedure }
 SP: TStrProc;                    { SP is a procedure that takes a string parameter }

 M: TMathFunc;                    { M is a function that takes a Double (real) parameter
                                      and returns a Double }
procedure FuncProc(P: TIntegerFunction);  { FuncProc is a procedure whose only parameter
                                             is a parameterless integer-valued function }


The previous variables are all procedure pointers--that is, pointers to the address of a procedure or function. If you want to reference a method of an instance object (see Classes and objects), you need to add the words of object to the procedural type name. For example

type
 TMethod = procedure of object;
 TNotifyEvent = procedure(Sender: TObject) of object;


These types represent method pointers. A method pointer is really a pair of pointers; the first stores the address of a method, and the second stores a reference to the object the method belongs to. Given the declarations

type
 TNotifyEvent = procedure(Sender: TObject) of object;
 TMainForm = class(TForm)
   procedure ButtonClick(Sender: TObject);
   ...
 end;
var
 MainForm: TMainForm;
 OnClick: TNotifyEvent


we could make the following assignment.

OnClick := MainForm.ButtonClick;

Two procedural types are compatible if they have

the same calling convention,
the same return value (or no return value), and
the same number of parameters, with identically typed parameters in corresponding positions. (Parameter names do not matter.)

Procedure pointer types are always incompatible with method pointer types. The value nil can be assigned to any procedural type.

Nested procedures and functions (routines declared within other routines) cannot be used as procedural values, nor can predefined procedures and functions. If you want to use a predefined routine like Length as a procedural value, write a wrapper for it:

function FLength(S: string): Integer;
begin
 Result := Length(S);
end;


Обрати особое внимание на то что подчёркнуто.


 
Kostafey ©   (2005-10-07 00:32) [9]

ВСЕ ПОНЯЛ, ИСПРАВИЛ И ВСЕ ДЕЙСТВИТЕЛЬНО РАБОТАЕТ !!!!!!!!!!

СПАСИБО ОГРОМНОЕ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

По сути-то получается, что
TFunc = function (x:real):real of object
и есть своего рода указатель, но явно это указывать не нужно как я начал мудрить : PFunc = ^TFunc

Я правильно понял ?


 
Eraser ©   (2005-10-07 00:49) [10]


> Kostafey ©   (07.10.05 00:32) [9]
>
> Я правильно понял ?

Правильно.



Страницы: 1 вся ветка

Форум: "Основная";
Текущий архив: 2005.10.30;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.48 MB
Время: 0.035 c
3-1126973127
Tonich
2005-09-17 20:05
2005.10.30
Числа в базе данных


2-1128443420
Alex_T
2005-10-04 20:30
2005.10.30
Подскажите плиз как корректно реализовать


1-1129013418
Gorez
2005-10-11 10:50
2005.10.30
janXMLparser2


14-1128671022
Andry
2005-10-07 11:43
2005.10.30
Web-сервер


14-1129112039
Mike Kouzmine
2005-10-12 14:13
2005.10.30
Подробности происхождения современного человека





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский