简体   繁体   English

如何访问像字节数组这样的字符串?

[英]How to access a string like an array of bytes?

I want to do the following but I get "Access violation" error. 我想执行以下操作,但出现“访问冲突”错误。

type Bin = array of byte;

var s:string;

begin
 s:='some string';
 Bin(s)[3]:=ord('X');
 caption:=s;
end;

Why this doesn't work ? 为什么这不起作用?

This does not work because AnsiString and a dynamic array of byte are incompatible types. 这不起作用,因为AnsiString和动态字节数组是不兼容的类型。 Your cast is invalid and anything can happen. 您的演员表无效,一切皆有可能。

As it turns out, your string is a literal. 事实证明,您的字符串是文字。 The compiler handles that by putting the string in read only memory. 编译器通过将字符串放入只读存储器来处理该问题。 Hence the access violation when you go behind its back. 因此,当您落后时就会发生访问冲突。

The solution is easy enough. 解决方案很容易。 Use the [] indexing operator on the string directly: 直接在字符串上使用[]索引运算符:

s[i] := ...;

When you do this, the compiler knows that the string is read-only, and copies it to writeable memory to allow you to modify it. 当您执行此操作时,编译器会知道该字符串是只读的,并将其复制到可写内存以允许您对其进行修改。

You say that you don't want to use ord() and chr() . 您说您不想使用ord()chr() I don't know why. 我不知道为什么 They are the correct things to use and, it's not as if they even result in any code being emitted. 它们是可以使用的正确东西,并且似乎并没有导致发出任何代码。 They are intrinsics that turn into no-ops. 它们是变成无操作的内在函数。

You state in a comment that you are coding an encryption algorithm. 您在注释中指出您正在编码加密算法。 This then points up the fundamental flaw in your approach. 然后指出了您的方法的根本缺陷。 Encryption algorithms operate on byte arrays. 加密算法在字节数组上运行。 Don't feed text into an encryption code. 不要将文本输入加密代码。 Convert to a byte array using some well-defined text encoding. 使用一些定义良好的文本编码转换为字节数组。 And then operate on byte arrays. 然后对字节数组进行操作。 And don't reinvent the wheel. 而且不要重新发明轮子。 Use an existing crypto library. 使用现有的加密库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM