2


I'm trying to call a C function from C#.
Here is the function from the C header file :

int __stdcall GetImageKN (unsigned short *ndat );

And from the documentation about this function :

ndat :
Pointer of the grayscale image data acquiring buffer.
Always secure the range image storage area using the application program.
The size of the range image data storage area should be:
160’ 120 ‘2 = 38400 bytes
The grayscales are returned as 8 bit that is doubled from 7-bit.

How do I invoke this function and read the image data ?
Thanks,
SW

4 Answers 4

2

30Kb is a small buffer. If your function runs quickly, you can rely on default marshaling behaviour and do this:

[DllImport ("your.dll")]
extern int GetImageKN (short[] ndat) ;

var buffer = new short[160 * 120] ;
var result = GetImageKN (buffer)  ;

Even if it can block for a long time, you can get away with this if you don't call this function on many threads at once.

1
  • No, because it is the default behaviour. Feb 8, 2011 at 21:01
1
[DllImport ("your.dll")]
extern int GetImageKN (IntPtr ndat);

will probably do...

EDIT

generally pointers are represented as IntPtr. you can create a managed array and Marshal it to IntPtr,

3
  • But one should pass an address of an array to the function. How can ndat represent such an array?
    – Vlad
    Feb 8, 2011 at 19:01
  • ndat is output, how do I read the array values from an IntPtr ? Feb 8, 2011 at 19:07
  • @Weis: it looks like ndat is parameter you are passing in, if you are expecting the function to modify it, you can decorate it with [Out] attribute and it will be modified. you can also marshal it back to managed array when you are done. go to pinvoke.net for tons of examples on how to use it.
    – Alex
    Feb 8, 2011 at 19:15
1

I would try the following:

[DllImportAttribute("your.dll", CallingConvention=CallingConvention.StdCall)]
extern int GetImageKN(
    [Out, MarshalAs(UnmanagedType.LPArray, SizeConst=38400)] ushort[] ndat);

Not really sure however.

0
ushort ndat= 123;

GetImageKN(ref ndat);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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