如何投放数组指针和回德尔福? [英] How to cast an array to pointer and back in Delphi?

查看:116
本文介绍了如何投放数组指针和回德尔福?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示在列字符串中的所有者绘制组合框。绘图程序可以在连击共享,如果我能以某种方式通过列规范的事件的OnDrawItem。一种自然的方式这样做,将列宽的数组传递在ComboBox.Tag属性,然后将它转换回一个数组。

I have an owner drawn combo box that displays the strings in columns. The drawing routine can be shared across combos if I can somehow pass the column specifications to the OnDrawItem event. A natural way to do so, would be to pass the array of column widths in the ComboBox.Tag property and then cast it back to an array.

当我定义列数组为:

const arrWidth :array[1..4] of integer = (100,100,100,70);

和Tag属性设置为:

ComboBox.Tag := integer(@arrWidth);

然后在事件的OnDrawItem,将它转换回一个数组:

and then in the OnDrawItem event, cast it back to an array:

Widths :array of integer;
Widths := pointer(ComboBox.Tag);

我可以看到数组元素罚款,但数组不知道它的长度。它似乎与各种随机值的要长得多。

I can see the array elements fine, but the array does not know it's length. It appears to be much longer with all sorts of random values.

我一直在使用动态数组想说,但我甚至不得到适当的列值。

I have tried using a dynamic array, but then I don't even get the proper column values.

推荐答案

强制类型转换是危险的,因为你去的类型检查系统之外。已经在这里抓到你。问题是,数组[1..4]整数的整数数组是不一样的类型。

Casts are dangerous because you go outside the type checking system. That has caught you out here. The issue is that array[1..4] of integer and array of integer are not the same type.

您需要声明您的数组作为一个独特的类型像这样

You need to declare your array as a distinct type like this

TWidthArray = array [1..4] of Integer;
PWidthArray = ^TWidthArray;

然后做您忠实的是这样的:

Then do your constant like this:

const 
  arrWidth: TWidthArray = (100,100,100,70);

当您需要将数组从组合框中提取做这样的:

When you need to extract the array from the combo box do it like this:

Widths: TWidthArray;
...
Widths := PWidthArray(ComboBox.Tag)^;

如果您需要使用动态数组长度,那么你就需要改变你的通用类型,以反映支持。不过,要注意,铸造到整数将在标签将绕过动态数组的引用计数。所以,你需要真正了解,如果你走这条路线,你在做什么。

If you need to support using dynamic array lengths then you would need to change your common type to reflect that. However, beware that casting to an Integer to put in Tag will bypass the reference counting of the dynamic array. So you need to really understand what you are doing if you go down that route.

最后一点。要是你想编译这个code为64位就会失败,因为这行:

One final point. If ever you wish to compile this code for 64 bit it will fail because of this line:

ComboBox.Tag := integer(@arrWidth);

因为整数是一个32位数据类型。相反,你应该使用 NativeInt 这是一个整数相同的宽度为指针。

since integer is a 32 bit data type. Instead you should use NativeInt which is is an integer the same width as a pointer.

ComboBox.Tag := NativeInt(@arrWidth);

这篇关于如何投放数组指针和回德尔福?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆