2
$\begingroup$

I have an external "C" DLL function which returns a pointer to an byte array as well as the number of array elements (bytes)

DLLEXPORT void dllfun(void **a, int *n);

Now I want to use

f=DefineDLLFunction["dllfun","dlllib.dll","void", {"void**","int*}]

to be able to call dllfun via f:

n=0;  
f[a,n]

such that being able to access the array a.

I am aware that if I could define the array a inside Mathematica prior to the call:

n=77;  
a=NETNew["System.Byte[]", n];
f[a,n]

then the dll function could access the array and fill it with some values. The problem is that the dll function uses ist own memory management such that I can not pass memory allocated by Mathematica. If it would help I have the info of the array size n already available in advance to the call.
It seems to me like I would need a version of NETNew for declaring a pointer to an array with known size n without actually reserving the memory for it.

Any hints welcome

$\endgroup$
  • $\begingroup$ corrected char* a to void ** a $\endgroup$ – Robert Nowak Mar 11 at 14:37
1
$\begingroup$

ok, after peeking around this is one solution:

(* DLLEXPORT void dllfun(void **a, int *n); // the C language part *)
Needs["NETLink`"];  
(* define f as a dll function with two parameters, 1. pointer to pointer, 2. pointer to int *)
f = DefineDLLFunction["dllfun", "dlllib.dll", "void", {"out IntPtr", "out int"}];  
ptr = NETNew["System.IntPtr"];  (* initialize pointer *)
n = 0; (* initialize length variable *)
f[ptr, n]; (* calling the dll function loads the pointer and the length *)
destination = NETNew["System.Byte[]",n] (* allocate destination *);  
LoadNETType["System.Runtime.InteropServices.Marshal"]; (* need for Marshal`Copy *)  
Marshal`Copy[ptr, destination, 0, n]; (* copy to destination *)   
result = destination//NETObjectToExpression; (* convert to Mathematica Table containing Byte values *)  
ReleaseNETObject[destination]; (* clean up *)  
ReleaseNETObject[ptr]; (* clean up *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.