views:

105

answers:

3

I'm using a DLL written in c++ in my C# project. I have been able to call functions within the DLL using this code:

[DllImport("hidfuncs", EntryPoint = "vm_hid_scan", ExactSpelling = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr VmHidScan();

Now I need to call a function that requres a custom type pointer. The Docs for the DLL layout the function like this:

hid_get_info(int n,PDEV_INFO *pdi)

I don't know how to use this custom pointer. Is this defined in the DLL? If so how can use it from C# project? If not do I need to include the header file in c#? Thanks in advance for your help.

A: 

You need to create a struct in C# that mirrors the C++ PDEV_INFO struct in C++.

You should apply [StructLayout(LayoutKind.Sequential)] to the struct and then copy the fields from the C++ struct (look at the header file) in order.

You can then write an extern method that takes the struct as a ref parameter.

SLaks
A: 

I'll safely assume PDEV_INFO* is a DEV_INFO**.

Use this in C#:

class DEV_INFO
{
    // fields go here
}

static class NativeMethods
{
    [DllImport...]
    public static extern int hid_get_info(int n, ref DEV_INFO pdi);
}
280Z28
That's *DEV_INFO, not **DEV_INFO.
Hans Passant
@nobugz: Not when `DEV_INFO` is declared in C# as a *class*.
280Z28
Ah, right. [StructLayout] is not optional on a class.
Hans Passant
+1  A: 

Given the "P" prefix, it looks like the real declaration is

hid_get_info(int n, DEV_INFO **pdi)

where DEV_INFO is a structure. You'll need to find the declaration of this structure and add it to your C# code with the [StructLayout] attribute. You'd then declare the function like this in your C# code:

[DllImport("blah.dll")]
private static extern something hid_get_info(int n, out IntPtr pdi);

and use Marshal.PtrToStructure() to obtain the structure value. Hopefully you don't have to free the structure, you'd be screwed.

A second interpretation is that "pid" returns an array of pointers to DEV_INFO structures. Somewhat likely given the "n" argument, which could well mean the number of elements in the array you pass to be filled by the function. In that case, pass an IntPtr[] and set "n" to its Length.

Hans Passant
@rros - I'm curious, which interpretation was correct?
Hans Passant