P/Invoke: method returning an array of Structures with char[]

G

Guest

Hi,

I have a written a DLL in C myself, and I want to use it in my C# app using
P/Invoke.

Two functions are returning an array of structures which are containing a
char[] field of known size.

I tried to write a P/Invoke code in C#. but I get an error when I run the
application...
I tried to search a lot of infos on how to convert structures and char[]
but I've never found a definited guide... could you please check my P/Invoke
..

Your help will be greatly appreciated! Thanks a lot!

Lionel Reyero

The C exports:

#define DllExport __declspec( dllexport )


DllExport typedef struct _AP
{
CHAR MAC_ADDR[18];
CHAR SSID[128];
LONG RSSI;
INT WEP;
INT INFR;
} AP, *AP_LIST;


DllExport typedef struct _ADAPTER
{
TCHAR Description[_MAX_PATH];
TCHAR Title[_MAX_PATH];
TCHAR ServiceName[_MAX_PATH];
} ADAPTER, *ADAPTER_LIST;


DllExport ADAPTER_LIST getWirelessAdapters(int* AdapterNumber);
DllExport int init_adapter(ADAPTER adapter);
DllExport int init();
DllExport AP_LIST poll(int sleeptime, int* APnumber);
DllExport BOOL StopZeroConfig();
DllExport BOOL StartZeroConfig();


==============
The C# P/Invoke code:

public struct AP
{
public string mac_addr;
public string ssid;
public long rssi;
public int wep;
public int infr;
}

public struct ADAPTER
{
public string description;
public string title;
public string serviceName;
}


//public static MyCallBackFunction c1;

[DllImport("TestSpotter.dll")]
public static extern int init();

[DllImport("TestSpotter.dll")]
public static extern ADAPTER[] getWirelessAdapters(out int
adaptersNumber);

[DllImport("TestSpotter.dll")]
public static extern int init_adapter(ADAPTER adapter);

[DllImport("TestSpotter.dll")]
public static extern AP[] poll(int sleepTime, out int apNumber);

[DllImport("TestSpotter.dll")]
public static extern bool StopZeroConfig();

[DllImport("TestSpotter.dll")]
public static extern bool StartZeroConfig();
 
P

Paul G. Tobey [eMVP]

What you really want to do, since the character arrays are of known size, is
create your own class for each structure and pass it to unmanaged code as an
array of bytes. This is done *all over the place* in OpenNETCF's SDF. You
might look at any of the types passed for P/Invoke in
OpenNETCF\Win32\DateTime.cs, for example. You basically flatten the
structure to an array of bytes, declare the C function as taking the array
of bytes, then use the public accessors of the class to get the
understandable fields of the structure (SSID, for example, which would grab
the bytes found at offset 18, if you really mean CHAR, not TCHAR), and
continuing for a given length...

Paul T.
 

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