PInvoke "Struct" Problem

A

angshuman.agarwal

Structure in C DLL
----------------------------
typedef struct IrData
{
unsigned short uiFormat;
unsigned short uiLength;
unsigned char* pchData;
} tagIrData;

Function in C DLL
----------------------------
short ConvertData(char* pchString, tagIrData* ptIrCode); ---> This
function fills the allocated structure with the respective field
values.

How should we write the PInvoke for this ? I have tried the method
below (with both struct & class) but my structure elements go for a
toss. Please correct me.

[StructLayout(LayoutKind.Sequential)]
internal class IrData
{
public ushort IrFormat;
public ushort IrCodeLength;
public byte[] IrCodeData;
}

[DllImport("SomeDll.dll")]
private static extern short ConvertData(string strData, IrData
data);

Thx in Advance.
 
M

Michael C

Structure in C DLL
----------------------------
typedef struct IrData
{
unsigned short uiFormat;
unsigned short uiLength;
unsigned char* pchData;
} tagIrData;

Function in C DLL
----------------------------
short ConvertData(char* pchString, tagIrData* ptIrCode); ---> This
function fills the allocated structure with the respective field
values.

How should we write the PInvoke for this ? I have tried the method
below (with both struct & class)

You can use either. If using a class pass by value and it gets passed by
reference, if using a struct you need to pass by reference. I almost always
use class because you can add functions to the class etc. Once that is
working the only problem will be the char* but I think that will work as it
is. The only other thing to check would be the layout of your structure, use
the FieldOffset attribute to make sure it has the exact layout you require
(although I don't think this will be required).

Michael
 
A

angshuman.agarwal

I did this, but no luck !

[StructLayout(LayoutKind.Sequential)]
public struct IrData
{
public ushort IrFormat;
public ushort IrCodeLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256]
public byte[] IrCodeData;
}

[DllImport("SomeDLL.dll")]
private static extern short ConvertData(string strData, ref
IrData data);
 
I

igd

Replace 'struct' with 'class' and initialize at least the array (public
byte[] lrCodeData = new byte[256];)
 

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