Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an unknown Interface to a Pointer?

Can I save an unknown interface to a pointer ?

For example I have an unknown interface and want to save it to a TreeNode Data?

var
  X : Inknown;

To save :

....  
  Node:=TreeView1.Items.Add;
  //Node.data:=x; //compiler won't allow this
  Node.data:=@x;
...  

To get :

...  
var
  //X:=Node.data; //compiler won't allow this too
  Pointer(X):=Node.data; //an exception caught
...  
like image 794
Theo Avatar asked Dec 26 '13 23:12

Theo


1 Answers

An interface is a pointer, so you can store it as-is (don't use the @ operator). However, to ensure the interface's lifetime, you have to increment/decrement its reference count manually for as long as the node refers to it, eg:

Node := TreeView1.Items.Add;
Node.Data := Pointer(x);
x._AddRef;

x := IUnknown(Node.Data);

procedure TMyForm.TreeView1Deletion(Sender: TObject; Node: TTreeNode);
begin
   IUnknown(Node.Data)._Release;
end;
like image 178
Remy Lebeau Avatar answered Jan 14 '23 21:01

Remy Lebeau