interop: passing C++ structs to C#

D

dvanderboom

How would I pass a structure like this by reference through an interop
call? I keep getting a NotSupportedException on the call that takes a
pointer to this structure as a parameter. The DLL I'm calling was
created by someone else in C++ and it's not a COM object.

The C++ definitions:

typedef struct {
int nPortIndex;
int nPortNumber;
TCHAR tszDeviceName[8];
DWORD dwMagic
DWORD dwReserved[5];
} RFID_FINDINFO;

DWORD WINAPI RFID_FindNext(
HANDLE hReader,
RFID_FINDINFO *lptRFIDFindInfo,
HANDLE hFind);

This is what I tried:

[StructLayout(LayoutKind.Sequential)]
public struct RFID_FINDINFO {
public int nPortIndex;
public int nPortNumber;
public StringBuilder tszDeviceName;
public UInt32 dwMagic;
public UInt32[] dwReserved;
};

[DllImport("RFIDAPI32.dll", EntryPoint="#149")]
public static extern uint FindFirst(
IntPtr hReader,
ref RFID_FINDINFO ptRFIDFindInfo,
ref IntPtr phFind);

Then when I called it, I did this to set up the struct:

RFID_FINDINFO fi = new RFID_FINDINFO();
fi.tszDeviceName = new StringBuilder("");
fi.tszDeviceName.Capacity = 8;
fi.dwReserved = new UInt32[5];

// This is the line it errors out on.
result = FindFirst(ReaderHandle, ref fi, ref FindHandle);
What am I doing wrong?
 
P

Paul G. Tobey [eMVP]

I think you're going to be better off using a byte array as the 'structure'
in managed code and creating property accessors that extract the
tszDeviceName, for example, from the byte array. There are quite a number
of examples of this in the OpenNETCF SDF. The .Net namespace, in
particular, does this all over the place.

Paul T.
 
D

dvanderboom

Is the dwReserved array going to pose a problem as well, since it's a
reference type inside a structure?
 
P

Peter Foot [MVP]

As long as the byte array you allocate for the structure allows 20 bytes for
these unused values it will not pose a problem. So you'll create a 48 byte
array and pass it into the function. You can get and set values from this
buffer using the BitConverter, Buffer and related classes, again see the
OpenNETCF code for examples.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top