Меню Закрыть

Implicit string cast from shortstring to string

Содержание

Guys I’m using Delphi XE3, and I’m having this error, I have tried to look at previous questions and tried to solve accordingly but the error wont go away. Anyone who has used XE3 please help me, am so frustrated. As still a novice in programming

the [dcc32 Warning] invoice_u.pas(92): W1057 Implicit string cast from ‘ShortString’ to ‘string’

Below is my code

1 Answer 1

We cannot tell which line the warning applies to, and we cannot see the types of all the variables in the code. However, the warning message is clear enough. Somewhere you do

where s is a string , alias for UnicodeString , and t is a ShortString . Since ShortString is always ANSI encoded, the compiler is warning you that you are making an implicit conversion from ANSI to UTF-16. It warns you because you ought to be aware of such conversions, and being implicit, it is not immediately obvious from reading the code.

The best way to solve the problem is to stop using the long deprecated ShortString type. There’s really no place for it today.

If you cannot bring yourself to do that then you may suppress the warning with an explicit conversion.

Of course, this provokes the explicit string cast warning W1059 but that warning is off by default.

Friday, October 03, 2008

Delphi 2009: Unicode

W1050 WideChar reduced to byte char in set expressions. Consider using ‘CharInSet’ function in ‘SysUtils’ unit

This compiler warning is commonly encounter in Delphi 2009. We should change all coding using characters set with CharInSet.

Delphi 2007: A in [‘a’, ‘b’]

Delphi 2009: CharInSet(A, [‘a’, ‘b’])

However, doing such changes will make the code not compatible with Delphi 2007. We may construct a CharInSet function for Delphi 2007:

Читайте также:  Kids online tracking watch operating instruction

The $if directive will restrict the code available for Delphi 2007 or older only.

W1057 Implicit string cast from ‘ShortString’ to ‘string’

The following code will raise a famous W1057 compiler warning in Delphi 2009:

var s: ShortString;
t: string;
begin
t := s;
end;

To eliminate the warning, just cast the ShortString variable as String and it is compatible with both Delphi 2007 and 2009:

var s: ShortString;
t: string;
begin
t := string(s);
end;

W1057 Implicit string cast from ‘AnsiString’ to ‘string’

The following code will raise a famous W1057 compiler warning in Delphi 2009:

var s: AnsiString;
t: string;
begin
t := s;
end;

To eliminate the warning, just cast the AnsiString variable as String and it is compatible with both Delphi 2007 and 2009:

var s: AnsiString;
t: string;
begin
t := string(s);
end;

W1058 Implicit string cast with potential data loss from ‘string’ to ‘AnsiString’

We must take extra care for this warning. Although using the famous cast method may solve the problem, we should only use it only if we understand what we are doing.

var s: AnsiString;
t: string;
begin
s := t;
end;

If we are very sure that t will contain only ansi string value, then we can perform the cast as follow safely:

var s: AnsiString;
t: string;
begin
s := AnsiString(t);
end;

This warning is usually happens in code invoke legacy external library (*.DLL) that supports PAnsiChar data type only.

4 comments:

Is there any performance hit when doing the explicit cast? i.e. string(RawByteString)

I think performance overhead can be neglected with today’s CPU.

I’m interested to know, whether the compiler sets up an explicit cast in the background, or some other mechanism?

Читайте также:  Sony a7 iii фокусировка по глазам

Quote:
"W1057 Implicit string cast from ‘AnsiString’ to ‘string’

The following code will raise a famous W1057 compiler warning in Delphi 2009:

var s: AnsiString;
t: string;
begin
t := s;
end;

To eliminate the warning, just cast the AnsiString variable as String and it is compatible with both Delphi 2007 and 2009:"

This can potentially be dangerous, now that Delphi uses Unicode by default. (Delphi XE as an example)

The reason is that Unicode and Ansi doesn’t have the same mapping from internal representation to character.

For applications using RS232 comport like Async Pro, it is important to use AnsiString when sending any strings to the RS232.

If you just cast the AnsiString to string to get rid of the warning, your code interfacing with async pro will no longer work.

m преобразование устаревшего кода в Delphi 2010.

Есть довольно много старых ShortStrings, таких как string [25]

Почему задание ниже:

заставить компилятор сгенерировать это предупреждение:

Там’Здесь нет потери данных. При каких обстоятельствах это предупреждение будет для меня полезной информацией?

как в AnsiStrings (начиная с D2009).

Преобразование из ShortString в UnicodeString может быть сделано только в предположении, что ShortStrings закодированы в кодировке ANSI по умолчанию, которая не является безопасным допущением.

но если я правильно помню, строки коротких строк — это, по сути, последовательность символов в стеке, тогда как обычная строка (AnsiString) на самом деле является ссылкой на местоположение в куче. Это может иметь разные последствия.

Я думаю, что также может быть разница с точки зрения кодирования, но яЯ не уверен на 100%.

безопасно (пока выВы используете ShortString по прямому назначению: для хранения строки символов, а не набора байтов, некоторые из которых могут быть 0), но это может повлиять на производительность, если вы делаете это много. Насколько я знаю, Delphi должен выделить память для новой строки Unicode, извлечь символы из ShortString в строку с нулевым символом в конце (это ‘почемуважно что этоэто правильно сформированная строка), а затем вызвать что-то вроде функции Windows API MultiByteToWideChar (). Не ракетостроение, но и не тривиальная операция.

Читайте также:  Рассчитать сколько лет по дате рождения

Присваивая его строковому типу, вы берете группу AnsiChars (один байт) и помещаете ее в группу WideChars (два байта). Компилятор может сделать это просто замечательно и достаточно умен, чтобы не потерять данные, но есть предупреждение, чтобы сообщить, что такое преобразование имело место.

косвенным образом преобразование однобайтовой символьной строки в UnicodeString. Это’s предупреждает вас на случай, если вы пропустили это, так как это может вызвать проблемы, если вы сделаете это по ошибке.

Чтобы он ушел, используйтеявный преобразование:

потому что вы можете потерять данные. Преобразование выполняется с использованием текущего 8-разрядного набора символов Windows, и некоторые наборы символов не определяют все значения от 0 до 255 или являются многобайтовыми наборами символов и, следовательно, не могут преобразовать все значения байтов.

Потеря данных может произойти на стандартном компьютере в стране с определенными стандартными наборами символов или на компьютере в США, который был настроен для другой локали, потому что пользователь много общается с людьми на других языках.

Например, если локальной кодовой страницей является 932, байтовые значения 129 и 130 будут оба преобразованы в одно и то же значение в строке Unicode.

В дополнение к этому преобразование включает вызов Windows API, который является дорогостоящей операцией. Если вы делаете много из них, это может замедлить ваше приложение.

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.