Native C DLL Call.

  • Thread starter Thread starter Sudeep
  • Start date Start date
S

Sudeep

Hi,
I need to create a wrapper for following native function scenario.
typedef struct _myinfo
{
char *buf;
int max_size;
}myinfo;

void getdata(struct myinfo *obj)
buf ==> is the pointer to the buffer which is filled by the getdate
function.
max_size ==> it the max. size of buf
Before calling getdata function i need to allocate the buffer and
assign its pointer to "buf" and and assign the "max_size" to the size
of that buffer. The function would just fill up that buffer to the
"max_size".
how do i deal with this ???
Thanks
Sudeep.
 
Sudeep said:
I need to create a wrapper for following native function scenario.
typedef struct _myinfo
{
char *buf;
int max_size;
}myinfo;

void getdata(struct myinfo *obj)
buf ==> is the pointer to the buffer which is filled by the getdate
function.
max_size ==> it the max. size of buf
Before calling getdata function i need to allocate the buffer and
assign its pointer to "buf" and and assign the "max_size" to the size
of that buffer. The function would just fill up that buffer to the
"max_size".
how do i deal with this ???

There are multiple ways of doing this, some more efficient than others.

If you still have the opportunity of writing additional native code, it
would be a good idea to write an extra function that takes "buf" and
"max_size" as parameters rather than struct members, because this allows for
much easier marshaling.

Otherwise, this should do:

internal static class NativeMethods {
[StructLayout(LayoutKind.Sequential)]
public struct MyInfo {
public IntPtr buf;
public int max_size;
}

[DllImport(...)]
public static extern void GetData([In] ref MyInfo obj);
}

...

public byte[] GetData(int length) {
MyInfo info = new MyInfo();
byte[] buffer = new byte[length];
try {
info.buf = Marshal.AllocHGlobal(length);
info.max_size = length;
NativeMethods.GetData(ref info);
Marshal.Copy(info.buf, buffer, 0, length);
} finally {
if (info.buf != IntPtr.Zero) Marshal.FreeHGlobal(info.buf);
}
return buffer;
}

Disclaimer: untested.

If you can use unsafe code, this can be rewritten to something with better
performance, but I wouldn't do that until you can show there's a need for
it. It's called "unsafe" for a reason.
 
Back
Top