Bruice
Bruice

Reputation: 663

C++ dll function to be called from Delphi - array parameter

I need to write C++ dll function, one of parameter is array. But his function will be called also from Delphi code. So I assume I can't just write std::vector or std::array. I've started to read about Delph now, but maybe some good soul will point me here to the proper solution :)

Upvotes: 1

Views: 268

Answers (1)

USauter
USauter

Reputation: 335

An array does not give the number of its elements. The number must therefore be supplied in a further parameter/route.

Strings are pointers. The value is therefore passed indirectly. A Delphi string does not exist in C++. The common type is PChar/LPWSTR.

Generell it is necessary to find out which language will provide the memory and when the memory will be released. When the call leaves the scope? Delphi cannot free the memory, but must read the values ​​from memory after calling C++.

In the case of an array, you have to either inform C++ afterwards that the memory can be released. The alternative would be to pass a callback method. The calling module (Delphi) can successively build the array itself via the callback.

Delphi functions are generated by default with register. Therefore switch the function prototype to stdcall.

type TFunc = function(var arr: integer; NewCount: integer): boolean; stdcall;

The address of the first array element comes via the parameter. Therefore, increment the read pointer to read out the next array element.

              var
                 Li     : integer;    
                 LpLfd  : PInteger;
                 //lplfd : PInteger absolute arr;
              begin
                SetLength(Result, NewCount);
                LpLfd := @arr; //instead of absolute 
                for Li := 0 to Pred(NewCount) do
                begin
                  Result[Li] := LpLfd^;
                  inc(LpLfd, 1);
               end;
             end; 

Upvotes: 3

Related Questions