Question

How can I copy a record ?

Asked by: delphi

Hi!

How can I copy a pointer to a record into another variable of the same record type ?

For example, I have the following code which obviously doesn't work but might give you an idea of what I want to accomplish.

PSOME_RECORD = ^TSOME_RECORD;
TSOME_RECORD = record
  a:PChar;
  b:PChar;
  c: Cardinal;
end;

And then I have the following

function getRecord(offset: integer) : PSOME_RECORD;
begin
  //This function works correctly
  Result := PSOME_RECORD_Func(offset);
end;

var
  FRecords : array of TSOME_RECORD;
begin
  SetLength(FRecords, 10);
  for i=0 to 9 do
    FRecords[I] := GetRecord(i)^;  <- this is the part I'm having problems with ...
end;

I know I can easily do this by copying every member explicitly, but since TSOME_RECORD might change at some time, I want a solution that will require the least maintenance possible.  I.E. copy the record-pointers directly into a records-array.

If the solution is simpler, FRecords can be switched to
FRecords : array of PSOME_RECORD, but the pointers must not point to the original result of GetRecord();

Thanks.
 

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-11-03 at 22:41:47ID20787019
Tags

copy

,

record

Topic

Delphi Programming

Participating Experts
4
Points
250
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. String and pChar
    I should assign a String-Value to a pChar-Variable. But the Compiler (Delphi 3 Prof) sais, 'incompatible types'. So is there any way to convert a String into a pChar ? I should use that, because the origin of the data, the String is stored in a binary file, more exactly in an...
  2. PChar problem
    These PChars are driving me nuts...they never give a result you'd expect...very unpredictable. I have a string array with about 20 character strings of 255 chars each. I simply want to loop thru them in a 'for' loop, and tack all these character strings together into 1 Pchar ...
  3. PCHAR and Edit.Text
    I'm filling a data structure that wants a pointer to a character passed in. The information is coming from several TEdit boxes on my form. temp_str := EditTagName.Text; newindex[1].name := PChar(AnsiString(temp_str)); If EditTagName.Text had the text 'NEW_TAG', the res...
  4. PChar / String
    A string (Pascal Style) in memory starts with a length. So a string, st, is set to 'Hello' it would be; 05 ord('H') ord('e') ord('l') ord('l') ord('o') in memory... right ? Well, if I cast this string into PChar by doing a PChar(st) then does delphi add a ascii zero to this...
  5. What is Cardinality
    Hi All, Can someone can explain me what is the cardinality of a database table? How de we specity the Cardinality of a table in a Database Design Report? Thanks in Advance, Regards, Badri.
  6. SetLength and pointers
    I'll try and confuse everyone as little as possible here. I have a record. It is called email_info. This record is basically an e-mail account. I have email_accounts which is an array of email_info. I add new accounts to a list (similar to a treeview i guess.) when the user...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: swift99Posted on 2003-11-03 at 23:04:52ID: 9676703

FRecord can be an array of PSomeRecord as easily as an array of Records

Then your code becomes


var
  FRecords : array of PSOME_RECORD; <- this is the easy part ...   :o)
begin
  SetLength(FRecords, 10);
  for i=0 to 9 do
    FRecords[I] := GetRecord(i);  <- this is the easy part ...   :o)
end;

 

by: snehanshuPosted on 2003-11-03 at 23:13:42ID: 9676732

delphi,
  If you want to "Copy" the "Contents" of the pointer to a record type, you could use
 FRecords[I] := TSOME_RECORD(GetRecord(i)^);

Here is my test case which shows that the contents of the pointer and the array are independent of each other:
Note: Record modified slightly for my convenience ;-)

  PSOME_RECORD = ^TSOME_RECORD;
  TSOME_RECORD = record
    a:integer;
    b:integer;
    c:integer;
  end;


procedure TForm1.Button2Click(Sender: TObject);
Var
  i: Integer;
  MyPtr: PSOME_RECORD;
begin
  For i := 1 to 10 do
  begin
    MyPtr := GetRecord(i);
    RecAry[i] := TSOME_RECORD(MyPtr^);//copy values contained in the pointer
    RecAry[i].a := RecAry[i].a * 10;//change array

    //pointer contents remain unchanged:
    Showmessage(Format('ary: %d, Ptr: %d',[RecAry[i].a, MyPtr^.a]));

  end;

end;

function TForm1.GetRecord(i: integer): PSOME_RECORD;
begin
//create a new record for now
 Result :=  AllocMem(Sizeof(TSOME_RECORD));
 Result^.a := i;
 result^.b := i*100;
 result^.c := i*1000;
end;


Hope that helps.
...Shu

 

by: snehanshuPosted on 2003-11-03 at 23:22:18ID: 9676755

Well, here's the complete code:

unit EnumUnit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, TypInfo;

type
  PSOME_RECORD = ^TSOME_RECORD;
  TSOME_RECORD = record
    a:integer;
    b:integer;
    c:integer;
  end;

  TForm1 = class(TForm)
    Button2: TButton;
    procedure Button2Click(Sender: TObject);
    function GetRecord(i:integer) : PSOME_RECORD;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  RecAry: Array [1 .. 10] of TSOME_RECORD;//I had missed this in the earlier post :-)

implementation

{$R *.dfm}

procedure TForm1.Button2Click(Sender: TObject);
Var
  i: Integer;
  MyPtr: PSOME_RECORD;
begin
  For i := 1 to 10 do
  begin
    MyPtr := GetRecord(i);
    RecAry[i] := TSOME_RECORD(MyPtr^);
    RecAry[i].a := RecAry[i].a * 10;
    Showmessage(Format('ary: %d, Ptr: %d',[RecAry[i].a, MyPtr^.a]))

  end;

end;

function TForm1.GetRecord(i: integer): PSOME_RECORD;
begin
//
 Result :=  AllocMem(Sizeof(TSOME_RECORD));
 Result^.a := i;
 result^.b := i*100;
 result^.c := i*1000;
end;

end.

Cheers!
...Shu

 

by: delphiPosted on 2003-11-03 at 23:39:41ID: 9676826

swift99,
your code stores pointers ... not the actual values.  If I later free all the memory involved in GetRecord(), FRecords will be affected also :(

snehanshu,
your code is basically what I ended up with, and everything works except for the null terminated PChars :(  ... is there any way I can copy the PChars also ?  Besides Cardinal and PChar, I also have an enum member ... the real record looks something more as:

type
  my_enum_values = (type1, type2, type3 ... typen);

TSOME_RECORD = record
  a: Cardinal;
  b: PChar;
  c: my_enum_values;
end;

I don't think there's any problem with 'c', but the PChar just messes things up :(

The reason for all this is TSOME_RECORD and GetRecord come from a DLL and the DLL uses too much memory;  I must free it as soon as I'm done with it and FRecords[] is used all through out the application.

Thanks for helping me out with this!

 

by: delphiPosted on 2003-11-04 at 00:01:17ID: 9676898

I am willing to increase the points to 500 if somebody gives me a good solution ...

I.E.  copies the records as specified above
frees FRecords from memory (including all of its PChar members) without explicitly making any name reference to them.

 

by: snehanshuPosted on 2003-11-04 at 00:02:14ID: 9676904

delphi,
  Handling pointer record members is a tough one! I am not sure I know any workaround for that :-(
  I shall try to find out, meanwhile, hopefully the better experts might help.
...Shu

 

by: delphiPosted on 2003-11-04 at 00:07:07ID: 9676921

snehanshu, after thinking the problem for a little longer I came to the conclusion it will require A LOT of memory handling and will only make things much harder to debug unless perfect code is provided.

I don't beleive this question will ever be answered to my satisfaction, but I do appreciate the effort and code you provided in your posts.

For the time being I will "hard-copy" each element of the record and will keep the question open.

Thanks for your help anyways.

 

by: snehanshuPosted on 2003-11-04 at 01:18:24ID: 9677164

delphi,
  I am not sure what's happening here, but it seems that Delphi makes the pointer thing would perhaps work just as you like :-)
  Check this:

  PSOME_RECORD = ^TSOME_RECORD;
  TSOME_RECORD = record
    a:integer;
    b:integer;
    c:integer;
    MyProb: PChar;
  end;

...

procedure TForm1.Button2Click(Sender: TObject);
Var
  i: Integer;
  MyPtr: PSOME_RECORD;
begin
  For i := 1 to 5 do
  begin
    MyPtr := GetRecord(i);
    RecAry[i] := TSOME_RECORD(MyPtr^);
    RecAry[i].a := RecAry[i].a * 10;
    RecAry[i].MyProb := 'Snehanshu';//Array says Snehanshu

//Snehanshu and Hello both still remain
    Showmessage(String(RecAry[i].MyProb) + String(MyPtr^.MyProb));
    FreeMem(MyPtr);
    Showmessage(String(RecAry[i].MyProb){ + String(MyPtr^.MyProb)});

//    Showmessage(Format('ary: %d, Ptr: %d',[RecAry[i].a, MyPtr^.a]))

  end;

end;

function TForm1.GetRecord(i: integer): PSOME_RECORD;
begin
//
 Result :=  AllocMem(Sizeof(TSOME_RECORD));
 Result^.a := i;
 result^.b := i*100;
 result^.c := i*1000;
 result^.MyProb := AllocMem(10);
 result^.MyProb := 'Hello';//DLL says Hello
end;

Cheers!
...Shu

 

by: snehanshuPosted on 2003-11-04 at 01:36:10ID: 9677244

Sorry, that wasn't a proper example.
So, the answer is that you cannot get RTTI for records in Delphi so you cannot do what you want.
the only solution would be to write a wrapper class: but your code would have to be recompiled every time your record structure changes.
...Shu

procedure TForm1.Button2Click(Sender: TObject);
Var
  i: Integer;
  MyPtr: PSOME_RECORD;
begin
  For i := 1 to 5 do
  begin
    MyPtr := GetRecord(i);
    RecAry[i] := TSOME_RECORD(MyPtr^);
    RecAry[i].a := RecAry[i].a * 10;
    Showmessage(String(RecAry[i].MyProb) + String(MyPtr^.MyProb));//Shows SHUSHU
    RecAry[i].MyProb[0] := 'U';
    RecAry[i].MyProb[1] := char(0);
    Showmessage(String(RecAry[i].MyProb) + String(MyPtr^.MyProb));//Shows UU
  end;
end;

function TForm1.GetRecord(i: integer): PSOME_RECORD;
begin
//
 Result :=  AllocMem(Sizeof(TSOME_RECORD));
 Result^.a := i;
 result^.b := i*100;
 result^.c := i*1000;
 result^.MyProb := AllocMem(10);
 result^.MyProb[0] := 'S';
 result^.MyProb[1] := 'H';
 result^.MyProb[2] := 'U';
 result^.MyProb[3] := char(0);

end;

 

by: Lee_NoverPosted on 2003-11-04 at 04:08:22ID: 9677940

well if your structures have pointers and you want to copy the "contents" of those pointers then there's no other way than 'hard copying' the values
if you used a class it'd be easier coz of RTTI
in your base class you'd just implement some general field copying method and that's it
note that all of your fields need to be published and the class must descend from TPersistent

 

by: Slick812Posted on 2003-11-05 at 21:33:56ID: 9692196

hello delphi, I am puzzled by your methods, it seems that for information exchange between a DLL, you'd use more Pointer oriented code. .
I would declare an Array Type of your TSOME_RECORD, and a pointer type to that array type, then you would just get a Pointer to the first Member of the DLL array and then you can access the data from your PMyRecAry variable

PSOME_RECORD = ^TSOME_RECORD;
TSOME_RECORD = record
  a:PChar;
  b:PChar;
  c: Cardinal;
end;

   PMyRecAry = ^TMyRecAry;
   TMyRecAry = Array[Word] of TSOME_RECORD;

Maybe some code like this

var
  PMRAry : PMyRecAry; // this is a Global variable that you can use in several procedures
 High1: Cardinal;  // this is the High (max index) of the array in the DLL, you do not say how you get this

procedure SetArrayPointer;
begin
  PSOME_RECORD( PMRAry) := GetRecord(0);
// now  PMRAr will have the CURRENT DATA in it, even if the DLL changes it, I am assuming that the DLL array is at a static address
end;

procedure UsePMRAry;
var
Amt1: Cardinal;
Str1: String;
begin
// you can easily access the data, and it will be upto date if DLL change it
Amt1 := 0;
for i := 0 to High1 do
  begin
  Str1 := Str1 + ' ' + PMRArray1^[i].a;
  Amt1 := Amt1 +  PMRArray1^[i].c;
  end;
end;

- - - - - - - - - - - - - - - - - - - - - - -
now if you need to KEEP this data after the DLL frees it, then you will need to just copy it, I will guess that the DLL will have some way to let you know when the Data Memory is released (maybe you FreeLibrary)

procedure WhateverFreeMemoryWarning;
var
PMRAry002 : PMyRecAry;
begin
PMRAry002 := AllocMem((High1+1)*SizeOf(TSOME_RECORD));
CopyMemory(PMRAry002, PMRAry,  (High1+1)*SizeOf(TSOME_RECORD));
// now just change the original pointer and you can keep using the code in other procedures
PMRAry := PMRAry002;
end;

you will need to FREE THE MEMORY if you ALLOCMEM, maybe when you app closes With FreeMem(PMRAry, (High1+1)*SizeOf(TSOME_RECORD));, be sure NOT to call FreeMem(PMRAry); if you are still using the DLL memory

this procedure will now still work even after you change the Pointer PMRAry

procedure UsePMRAry;
var
Amt1: Cardinal;
Str1: String;
begin
Amt1 := 0;
for i := 0 to High1 do
  begin
  Str1 := Str1 + ' ' + PMRArray1^[i].a;
  Amt1 := Amt1 +  PMRArray1^[i].c;
  end;
end;

 

by: Slick812Posted on 2003-11-05 at 21:37:27ID: 9692213

Str1 := Str1 + ' ' + PMRArray1^[i].a;

should be
Str1 := Str1 + ' ' + PMRArray^[i].a;

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...