Alasdair Stark
Alasdair Stark

Reputation: 1281

Pass array by reference from Delphi 7 to C++ Dll

Here is the C++ function exposed through the DLL:

double my_exposed_cpp_function(int* my_array){
 int i = my_array[2]; /* i should be 3 */
 my_array[2]++;
 return 0;
}

Here is the declaration of my Delphi function

function dll_function(var my_array: array of integer): Real; stdcall; external myDLL name 'my_exposed_cpp_function';

Here is what I would like to do in the Delphi function

procedure talk_to_dll();
var
 return_value: Real;
 my_array: array[0..2] of integer;
 final_value: integer;
begin
 my_array[0] = 1;
 my_array[1] = 2;
 my_array[2] = 3;
 return_value := dll_function(my_array);
 final_value = my_array[2]; /* my_array[2] should now be 4 */
end;

Hopefully that example makes my intentions clear. I can use this setup to work with simpler data types so I know that the communication between Delphi and the dll is fine. What do I need to change to get this working?

Upvotes: 2

Views: 2212

Answers (1)

David Heffernan
David Heffernan

Reputation: 612784

A Delphi open array is actually passed using two parameters: the address of the first element, and the element count minus one.

To call your C++ function you cannot use an open array. Simply declare the function as receiving a pointer to the first element:

function dll_function(my_array: PInteger): Real; stdcall; 
    external myDLL name 'my_exposed_cpp_function';

Call it like this:

return_value := dll_function(@my_array[0]);  

At some point you may want to let the array length vary dynamically. As it stands the code assumes that the array has three elements. For more generality you would pass an extra parameter specifying the array length.

I'm assuming that the C++ function really is stdcall although nothing in the question makes that explicit.

Upvotes: 6

Related Questions