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

Вниз

Пара вопросов по Delphi   Найти похожие ветки 

 
Stalp ©   (2007-01-09 19:18) [0]

В институте задали ответить на вопросы. Все перерыл, нигде не могу найти нормальные ответы.
Вот вопросы:

1. Назначение библиотеки VCL.
2. Тип данных PChar и его преимущества над типом String.

Может кто-нибудь подскажет ответы? И если можно, пожалуйста, поподробнее.


 
Ega23 ©   (2007-01-09 19:24) [1]

2.

A PChar is a pointer to a null-terminated string of characters of the type Char. Each of the three character types also has a built-in pointer type:

A PChar is a pointer to a null-terminated string of 8-bit characters.
A PAnsiChar is a pointer to a null-terminated string of 8-bit characters.
A PWideChar is a pointer to a null-terminated string of 16-bit characters.

PChars are, with short strings, one of the original Object Pascal string types. They were created primarily as a C language and Windows API compatibility type.

A string represents a sequence of characters. Object Pascal supports the following predefined string types.

Type Maximum length Memory required Used for
ShortString 255 characters 2 to 256 bytes backward compatibility
AnsiString ~2^31 characters 4 bytes to 2GB 8-bit (ANSI) characters
WideString ~2^30 characters 4 bytes to 2GB Unicode characters;
COM servers and interfaces
AnsiString, sometimes called the long string, is the preferred type for most purposes.
String types can be mixed in assignments and expressions; the compiler automatically performs required conversions. But strings passed by reference to a function or procedure (as var and out parameters) must be of the appropriate type. Strings can be explicitly cast to a different string type (see Typecasts).
The reserved word string functions like a generic type identifier. For example,

var S: string;

creates a variable S that holds a string. In the default {$H+} state, the compiler interprets string (when it appears without a bracketed number after it) as AnsiString. Use the {$H–} directive to turn string into ShortString.
The standard function Length returns the number of characters in a string. The SetLength procedure adjusts the length of a string.
Comparison of strings is defined by the ordering of the characters in corresponding positions. Between strings of unequal length, each character in the longer string without a corresponding character in the shorter string takes on a greater-than value. For example, “AB” is greater than “A”; that is, "AB" > "A" returns True. Zero-length strings hold the lowest values.

You can index a string variable just as you would an array. If S is a string variable and i an integer expression, S[i] represents the ith character—or, strictly speaking, the ith byte—in S. For a ShortString or AnsiString, S[i] is of type AnsiChar; for a WideString, S[i] is of type WideChar. The statement MyString[2] := "A"; assigns the value A to the second character of MyString. The following code uses the standard UpCase function to convert MyString to uppercase.

var I: Integer;

begin
 I := Length(MyString);
 while I > 0 do
 begin
   MyString[I] := UpCase(MyString[I]);
   I := I - 1;
 end;
end;

Be careful indexing strings in this way, since overwriting the end of a string can cause access violations. Also, avoid passing long-string indexes as var parameters, because this results in inefficient code.
You can assign the value of a string constant—or any other expression that returns a string—to a variable. The length of the string changes dynamically when the assignment is made. Examples:

MyString := "Hello world!";

MyString := "Hello " + "world";
MyString := MyString + "!";
MyString := " ";               { space }
MyString := "";                { empty string }


 
Anatoly Podgoretsky ©   (2007-01-09 19:26) [2]

> Stalp  (09.01.2007 19:18:00)  [0]

В самом название все и зашифровано

1. Visual Component Library
2. Pointer Char - преимуществ нет, поскольку String совместим с PChar


 
kaZaNoVa ©   (2007-01-09 19:30) [3]

String лучше и удобнее в общем случае ..
а PChar обычно требуют разные АПИ-функции


 
Dmitrij_K   (2007-01-09 19:39) [4]

1. http://ru.wikipedia.org/wiki/VCL


 
ors_archangel ©   (2007-01-09 20:09) [5]


>  [D2, D3, D4, D5, D6, D7, D2005, 95/98, ME, NT4, 2000, XP, 2003]

И как же это у тебя всего столько установлено? А такие вещи спрашиваешь...


 
tesseract ©   (2007-01-09 23:31) [6]


> 2. Pointer Char - преимуществ нет, поскольку String совместим
> с PChar


> String лучше и удобнее в общем случае ..а PChar обычно требуют
> разные АПИ-функции


Pchar быстрее, ибо не являеться массивом хранящим размер свой, часто применяеться для перевода чёрт-знает чего в указатель :-).


 
Anatoly Podgoretsky ©   (2007-01-09 23:36) [7]

> tesseract  (09.01.2007 23:31:06)  [6]

> Pchar быстрее, ибо не являеться массивом хранящим размер свой

Именно поэтой причине он как раз более медленный и чем длиннее строка тем медленнее.
И видимо ты пропустил мимо ушей фразу, что String полностью совместим с PChar
Он имеет часть полностью совместимую с PChar + дополнительный блок для расширенной работы.


 
tesseract ©   (2007-01-10 00:09) [8]


> Он имеет часть полностью совместимую с PChar + дополнительный
> блок для расширенной работы.

Поэтому и медленнее при интесивной работе, где то в RSDN видел тесты работы. PCHAR - указатель, string - массив с соответсвующими накладными расходами на операции с блоком расширенной работы :-)


> String полностью совместим с PChar

из Справки TD, но справедливо для всех версий Delphi.

Long string to PChar conversions are not automatic. Some of the differences between strings and PChars can make conversions problematic:

Long strings are reference-counted, while PChars are not.
Assigning to a string copies the data, while a PChar is a pointer to memory.
Long strings are null-terminated and also contain the length of the string, while PChars are simply null-terminated.


ЗЫ: любой указатель в Delphi хранит свой размер, так что не совсем точно.


 
Anatoly Podgoretsky ©   (2007-01-10 00:22) [9]

> tesseract  (10.01.2007 00:09:08)  [8]

Никаких накладных расходов, просто указание компилятору считать указатель не на строку, а на array of char и нет никакой разницы, будешь работать как с естественным указателем.


 
koha ©   (2007-01-10 02:23) [10]

- Сочуствую бедному студенту.


 
ors_archangel ©   (2007-01-10 02:32) [11]


>  любой указатель в Delphi хранит свой размер, так что не
> совсем точно.

указатель хранит лишь адрес, вот если память под указатель выделена GetMem, тогда размер хранится в загловке блока:

function GetBlockSize(p: pointer): integer;
begin
 if p = nil then
   Result := -1
 else
   Result := Integer(Pointer((Integer(p) - 4))^) and $7FFFFFFC - 4;
end;


 
icWasya ©   (2007-01-10 09:52) [12]

Вот ещё про PChar
http://russian.joelonsoftware.com/Articles/BacktoBasics.html


 
tesseract ©   (2007-01-10 10:05) [13]


> указатель хранит лишь адрес, вот если память под указатель
> выделена GetMem, тогда размер хранится в загловке блока:
>


Я про это и говорю.



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

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

Наверх





Память: 0.49 MB
Время: 0.045 c
2-1168629063
Pasha L
2007-01-12 22:11
2007.01.28
Странная ошибка в for


15-1168330882
zdm
2007-01-09 11:21
2007.01.28
office 2007 vs bds2006 в vista


1-1165418608
newbie2
2006-12-06 18:23
2007.01.28
Модераторы почему закрыли тему?


15-1167852215
vidiv
2007-01-03 22:23
2007.01.28
Ктонить может дать 100 wmr на 1 день...


15-1167937516
serko
2007-01-04 22:05
2007.01.28
Синхронизациия времени...





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
Английский Французский Немецкий Итальянский Португальский Русский Испанский