MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: NET/Link return array from C++

  • To: mathgroup at smc.vnet.net
  • Subject: [mg61156] Re: [mg60978] NET/Link return array from C++
  • From: Todd Gayley <tgayley at wolfram.com>
  • Date: Tue, 11 Oct 2005 03:22:37 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

At 03:08 AM 10/6/2005, Lars Schouw wrote:
>I am having some problems returning an array back from C++.
>
>I would expect {100.,100.,100} coming back in my example.
>Can anyone explain what I do wrong?
>
>C++
>void Test123(double x[], int size, double* result)
>{
>       for (long i = 0 ; i < size; i ++)
>                 *(result+i) = 100.;
>}
>
>NoteBook
>
>In[1]:= Needs["NETLink`"];
>TEST123 = DefineDLLFunction["ErrorFunctionA","mydll.dll",
>"Void",{"double[]", "long", "out double"}];
>
>input1=MakeNETObject[{1., 2., 3.}];
>res=MakeNETObject[{0.0,0.0, 0.0}];
>
>TEST123[input1, 3, res]
>
>NETObjectToExpression[res]
>
>100


Lars,

Dealing with array arguments that are written into by DLL functions is a 
bit tricky. I find that I have to remind myself of the rules for handling 
them every time I face a question about the subject.

You have the right idea in that you need to explicitly create a .NET array 
object (your 'res' variable) to hold the output. Simply passing in a 
Mathematica list will not work because you will have no way to retrieve the 
modified array values.

Your problem is with the "out double" type in DefineDLLFunction. When .NET 
marshals an "out double" argument into and back out of a DLL call, it 
treats it as the address of a double, not the beginning of a block of 
memory that might hold an array (after all, how could it know the length of 
the array?) The solution is to use the type "double[]" instead of "out double":

    TEST123 = DefineDLLFunction["ErrorFunctionA","mydll.dll", "Void", 
{"double[]", "long", "double[]"}];

Incidentally, those are exactly the array types you would use if you were 
declaring this external function in a C# program. It is generally the case 
that you can use the exact same types in DefineDLLFunction as you would in 
a C# or VB .NET declaration.


Todd Gayley
Wolfram Research



  • Prev by Date: Re: Re: Reevaluation of conditional arguments when the condition has changed
  • Next by Date: Re: SameTest in Union
  • Previous by thread: Re: NET/Link return array from C++
  • Next by thread: Re: NET/Link return array from C++