How to handle the content between unmanaged dll and C# - c#

Hi i got problems to handle information between an unmanaged dll and my C# code.
The function in my C dll is:
int import_large_string(struct sha_struct *sha_s,
const char *large_string);
That import the large_string and transform into sha_s, the struct sha_struct is the following:
struct sha_struct
{
struct information *info;
struct info_cfg cfg;
};
And the information struct is something like
struct information
{
int version;
char serial_number[16];
uint16_t exp_date;
};
In C# i imported the function import_large_string like this:
[DllImport("functionalDLL.dll", EntryPoint = "import_large_string", CharSet = CharSet.Ansi)]
public static int import_large_string(ref sha_struct sha_s, string large_string);
When i called the function, it suppose to store information in sha_struct sha_s, but i only have a random 8 digit number in sha_s.information.version not in the whole struct, what am I doing wrong?
Edited
My structs in C# are:
[StructLayout(LayoutKind.Sequential)]
public struct sha_struct
{
public information t;
public info_cfg cfg;
};
[StructLayout(LayoutKind.Sequential)]
public struct information
{
public int version;
public string serial_number;
public ushort exp_date;
};
[StructLayout(LayoutKind.Sequential)]
public struct info_cfg
{
public string release_version;
public string release_string;
public string release_password;
};

As pointed out by #DavidHeffernan, you want to use the MarshalAs attribute on your string field:
[StructLayout(LayoutKind.Sequential)]
public struct information
{
public int version;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]
public string serial_number;
public ushort exp_date;
};
As illustrated on this documentation link.

Related

how to convert c struct with void* to c#

I'm write a plugin with c# . the program with c# will use a dll which writes by c ,so I have to call c function in my c# program ,but unfortunately the c function's parameter is a struct and it is so complex that I never find any
help information about how to convert it to c# parameter.
the struct has an embedded function and void* parameter ,I didn't find anyway to convert them to c#.
the struct is mostly like this
struct first_struct{
char* parameter1;
int parameter2;
unsigned long parameter3;
unsigned short parameter4;
void* parameter5;
int (*parameter6)(int,void *);
second_struct parameter7;
};
struct second_struct{
char parameter8[64] ;
char parameter9[256];
};
I want change this c struct to c# struct but I have no idea how to do it
thanks #Biesi Grr and #Ian Abbott ‘s help it sames that I can change the c struct to c# like that.
public delegate int parameter6(int volcnt, System.IntPtr vod);
[StructLayout(LayoutKind.Sequential)]
public struct csharp_firstSturct
{
[MarshalAs(UnmanagedType.LPStr)]
public string parameter1;
public int parameter2;
public ulong parameter3;
public ushort parameter4;
public System.IntPtr parameter5;
public parameter6 m_parameter6;
}
but I still has no idea about how to convert parameter7 from C to C#,what should I do to convert parameter7 form c to c#.
Assuming your char arrays are null terminated strings you can do it the following way
public delegate int parameter6(int volcnt, System.IntPtr vod);
[StructLayout(LayoutKind.Sequential)]
public struct csharp_firstSturct
{
[MarshalAs(UnmanagedType.LPStr)]
public string parameter1;
public int parameter2;
public ulong parameter3;
public ushort parameter4;
public System.IntPtr parameter5;
public parameter6 m_parameter6;
[MarshalAs(UnmanagedType.Struct)]
public second_struct parameter7;
}
[StructLayout(LayoutKind.Sequential)]
public struct second_struct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string parameter8;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string parameter9;
}

Marshalling nested struct from C# to C++ DLL

I am trying to call a function from C# to a .DLL written in Borland C++ whose signature is:
extern "C" __declspec(dllexport) ls50errortype __stdcall Ls50P2Open(ls50p2apiconfiginfostruct &configinfo);
The corresponding call in C#:
[DllImport("C:\\Lumistar\\LDPS_8x\\Ls50P2_Dll.dll", EntryPoint = "Ls50P2Open", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true)]
public static extern void Ls50P2Open(ref ls50p2apiconfiginfostruct configinfo);
The structure of interest (ls50p2apiconfiginfostruct) is composed of nested structures and enums (copied from the C++ header):
typedef enum
{
MFMODEL_LS50P1,
MFMODEL_4422PCI,
MFMODEL_LS50P2,
MFMODEL_LS70P2,
MFMODEL_LS5070,
MFMODEL_LAST
}ecardmodel;
typedef enum
{
CHANNELDEVICE_NONE,
CHANNELDEVICE_50,
CHANNELDEVICE_70,
CHANNELDEVICE_LAST
}ls50p2channeldevicetype;
typedef enum
{
LS50V2DCARD_NONE,
LS50V2DCARD_40V1_10,
LS50V2DCARD_40V1_20,
LS50V2DCARD_40V2_10,
LS50V2DCARD_40V2_20,
LS50V2DCARD_38,
LS50V2DCARD_LAST
}ls50p2daughtercardtype;
typedef struct
{
bool HasDaughterCard;
ls50p2daughtercardtype DCardType;
bool SpecialStatusCapable;
int MaxBitsyncInputs;
bool HasBitsyncConfidenceLevel;
bool HasBitsync2ndCh;
bool SpecialStatusCapable2ndCh;
bool HasBitsyncConfidenceLevel2ndCh;
ls50p2daughtercardtype DCardType2ndCh;
int MaxBitsyncInputs2ndCh;
}ls50p2daughtercardinfostruct;
typedef struct
{
ecardmodel DeviceModel;
ls50p2channeldevicetype ChannelDataTypeAry[2];
ls50p2daughtercardinfostruct DaughterCardInfo;
bool HasExtendedBertPatterns;
int FirmwareVersionAry[2];
int NumPremodFiltersAry[2];
double Ls50SimPreModFilterKhzAry[2][LS50V2_MAX50SIMPREMODFILTERS];
double Ls50SimMinFmDeviationKhzAry[2];
double Ls50SimMaxFmDeviationKhzAry[2];
}ls50p2cardconfigstruct;
typedef struct
{
unsigned char *DataBuf;
HANDLE hNewDataRdy;
DWORD MaxBufLength;
DWORD CurrentBufLength;
int NumHeaderBytes;
}ls50p2carddatastruct;
typedef struct
{
ls50p2cardconfigstruct CardConfigInfo[MAXMFCARDS];
int Ls50P2CardCount;
ls50p2carddatastruct DataInfo[MAXMFCARDS][2];
}ls50p2apiconfiginfostruct;
Here's the corresponding struct in C#:
public enum ecardmodel
{
MFMODEL_LS50P1,
MFMODEL_4422PCI,
MFMODEL_LS50P2,
MFMODEL_LS70P2,
MFMODEL_LS5070,
MFMODEL_LAST
}
public enum ls50p2channeldevicetype
{
CHANNELDEVICE_NONE,
CHANNELDEVICE_50,
CHANNELDEVICE_70,
CHANNELDEVICE_LAST
};
public enum ls50p2daughtercardtype
{
LS50V2DCARD_NONE,
LS50V2DCARD_40V1_10,
LS50V2DCARD_40V1_20,
LS50V2DCARD_40V2_10,
LS50V2DCARD_40V2_20,
LS50V2DCARD_38,
LS50V2DCARD_LAST
}
[StructLayout(LayoutKind.Sequential)]
public struct ls50p2daughtercardinfostruct
{
public bool HasDaughterCard;
public ls50p2daughtercardtype DCardType;
public bool SpecialStatusCapable;
public int MaxBitsyncInputs;
public bool HasBitsyncConfidenceLevel;
public bool HasBitsync2ndCh;
public bool SpecialStatusCapable2ndCh;
public bool HasBitsyncConfidenceLevel2ndCh;
public ls50p2daughtercardtype DCardType2ndCh;
public int MaxBitsyncInputs2ndCh;
}
[StructLayout(LayoutKind.Sequential)]
public struct ls50p2cardconfigstruct
{
public ecardmodel DeviceModel;
public ls50p2daughtercardtype[] ChannelDataTypeAry;
public ls50p2daughtercardinfostruct DaughterCardInfo;
public bool HasExtendedBertPatterns;
public int[] FirmwareVersionAry;
public int[] NumPremodFiltersAry;
public double[] Ls50SimPreModFilterKhzAry;
public double[] Ls50SimMinFmDeviationKhzAry;
public double[] Ls50SimMaxFmDeviationKhzAry;
}
[StructLayout(LayoutKind.Sequential)]
public struct ls50p2carddatastruct
{
public StringBuilder DataBuf;
public IntPtr hNewDataRdy;
public uint MaxBufLength;
public uint CurrentBufLength;
public int NumHeaderBytes;
}
[StructLayout(LayoutKind.Sequential)]
public struct ls50p2apiconfiginfostruct
{
public ls50p2cardconfigstruct[] CardConfigInfo;
public int Ls50P2CardCount;
public ls50p2carddatastruct[,] DataInfo;
}
Here's the code in C# that I use to call the function:
ls50p2apiconfiginfostruct lscfg = new ls50p2apiconfiginfostruct();
lscfg.CardConfigInfo = new ls50p2cardconfigstruct[8];
for (int i = 0; i < 8; i++)
{
lscfg.CardConfigInfo[i].ChannelDataTypeAry = new ls50p2daughtercardtype[2];
}
lscfg.DataInfo = new ls50p2carddatastruct[8, 2];
Ls50P2Open(ref lscfg);
I have tried making this struct in C# but I haven't had much success (problems with enums, 2D arrays, fixed sized buffers). What is the correct way to create this structure in C#? Would this need to be done in an unsafe context?
Now for some reason I get the following error when running the code:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Library.dll
Additional information: Old format or invalid type library. (Exception from HRESULT: 0x80028019 (TYPE_E_UNSUPFORMAT))
What does your C# structure looks like. Are you using the StructLayoutAttribute?
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx
You can use it with the option sequential so you just would have to fill your c# structure with fields in the right order.
I believe the array problem is more or less answered here; Improper marshaling: C# array to a C++ unmanaged array
The accepted answer shows how to safely marshal a dynamically allocated array.
As for the enums, they shouldn't pose any problems, there is a clean 1:1 mapping. In fact, I would do it as described in this msdn post; http://blogs.msdn.com/b/abhinaba/archive/2007/08/27/sharing-enums-across-c-and-c.aspx
You can simply define all your enums in a .cs file then include it in both projects and everything will work fine.

char[] array equivalent in c#

i have a c++ struct which has char[20] like below, and it is packed.
#pragma pack(push, temp_aion_packed, 1)
struct temp
{
char x[20];
char y[20];
};
#pragma pack(pop, temp_aion_packed)
now how can i write this struct in c# so that both are same. i have written like this in c#
[DataContract]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public class temp
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string x;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string y;
}
below is the pinvoke declaration in c#
[DllImport("rmsCAPI.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "OrderRequirement")]
public static extern int OrderRequirement(ref temp tmp);
c++ function that calls this struct as parameter
long __stdcall OrderRequirement(struct temp *tmp)
{
string p="";
string q="";
p=temp->x;
q=temp->y;
char buff[2048];
sprintf(buff,"p: %s\n q: %s\n x: %s\n y: %s\n",p,q,temp->x,temp->y);
}
but when i do like this in c# it is giving me the junk data in c++, when i assign values for them in c#. Can any one please assist.
Thank you all for help on the above one, but now i got a new problem which is an extension of this, i am providing everything in detail below.
My structures in c++
#pragma pack(push, temp_aion_packed, 1)
struct temp
{
long req;
struct type m_type;
short id;
char x[20];
char y[20];
};
#pragma pack(pop, temp_aion_packed)
#pragma pack(push, type_aion_packed, 1)
struct type
{
short i;
};
#pragma pack(pop, type_aion_packed)
i have written equivalent c# structs like this
[DataContract]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public struct temp
{
[DataMember]
public long req;
[DataMember]
[MarshalAs(UnmanagedType.Struct)]
public type m_type;
[DataMember]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string x;
[DataMember]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string y;
}
[DataContract]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public struct type
{
[DataMember]
public short i;
}
below is my c# pinvoke
[DllImport("rmsCAPI.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "OrderRequirement")]
public static extern int OrderRequirement(ref temp tmp);
below is my c++ method that calls struct as parameter
long __stdcall OrderRequirement(struct temp *tmp)
{
char buff[2048];
sprintf(buff,"req: %ld \n id: %d \n x: %s\n",tmp->req,tmp->id,tmp->x);
}
now the problem i am getting is as i have structure variable m_type(of struct "type") declared in struct temp, the variables declared before (long req)that are printing fine in my c++ program but the variable declared after that are not giving me any output. So i think the declaration of structures in c# is messing up and i am unable to figure it out so can any one please help.
You declared the struct as a class in C#. That's fine, but it means that any variable of that type is already a reference. So you don't need to pass by ref. When you pass a class by ref you end up passing a pointer to a pointer to the object. That's one level of indirection too many.
The P/invoke in the C# code should therefore be like this:
public static extern int OrderRequirement(temp tmp);
The other way to fix it is to leave the ref in the function declaration, but to declare the temp type as a struct rather than a class. That's because a struct is a value type. A variable whose type is a struct is a value rather than a reference.
Both solutions work, it's up to you which you choose.
There is another problem in your C++ code.
sprintf(buff,"p: %s\n q: %s\n x: %s\n y: %s\n",p,q,temp->x,temp->y);
You are passing p and q, which are of type std::string to printf and expecting the %s format string to print them. That's an error. You need to call c_str() on the strings. Like this:
sprintf(
buff,
"p: %s\n q: %s\n x: %s\n y: %s\n",
p.c_str(),q.c_str(),temp->x,temp->y
);
The problem with your update is that long is 32 bits in Windows C++ and 64 bits in C#. You need to declare it as int in C#. And you missed the id field altogether.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public struct temp
{
[DataMember]
public int req;
[DataMember]
public type m_type;
[DataMember]
public short id;
[DataMember]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string x;
[DataMember]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string y;
}

How to convert a C++ Struct with Union into C#?

Guys I am having difficulties on retrieving struct member values after calling a function in the DLL. I tried to convert the C++ codes into C# but I’m not sure if it is correct or not. Please help me understand my mistakes here (if there is) and how to correct.
My problem here is I can’t correctly retrieved the values of the INNER STRUCTS (Union) after I called the ReceiveMessage function from the DLL. Like for example m_objMsg.MsgData.StartReq.MsgID is always 0.
But when I try to use the C++ .exe program, the MsgID has a correct value. (not 0)
C++ Code:
extern int ReceiveMessage(SESSION, int, Msg*);
typedef struct
{
char SubsId[15];
int Level;
char Options[12];
} ConxReq;
typedef struct
{
char MsgId[25];
} StartReq;
typedef struct
{
long Length;
short Type;
union
{
ConxReq oConxReq;
StartReq oStartReq;
} Data;
} Msg;
/////////////////////////////////////////////////////
Msg oMsg;
int rc=ReceiveMessage(Session, 0, &oMsg);
switch(rc)
{
case 0:
switch(oMsg.Type)
{
case 0: // ConxReq
…
break;
case 1: // StartReq
…
break;
…
}
And here is my attempt to convert this into c#:
[DllImport("MyDLL.dll",
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi)]
protected static extern Int32 ReceiveMessage(IntPtr session,
Int32 nTimeOut,
[MarshalAs(UnmanagedType.Struct)] ref Msg ptrMsg);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ConxReq
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string SubsId;
public Int32 Level;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
public string Options;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct StartReq
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 25)]
public string MsgId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
protected struct Msg
{
public int Length;
public Int16 Type;
public Data MsgData;
}
StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct Data
{
[FieldOffset(0)]
public ConxReq oConxReq;
[FieldOffset(0)]
public StartReq oStartReq;
}
Msg m_objMsg = new Msg();
m_objMsg.MsgData = new Data();
m_objMsg.MsgData.oConxReq = new ConxReq();
m_objMsg.MsgData.oStartReq = new StartReq();
int rc = ReceiveMessage(m_Session, nTimeOut, ref m_objMsg);
then the SWITCH Condition
And If I add this struct inside the UNION for c++ and c#...
I've got an error stating the "... incorrectly align" or "...overlapped..."
c++
ConxNack oConxNack;
typedef struct
{
int Reason;
} ConxNack;
[StructLayout(LayoutKind.Sequential)]
public struct ConxNack
{
public int nReason;
}
[FieldOffset(0)]
public ConxNack oConxNack;
Thank you so much in advance for your time and help...
Akash is right, have a look here: http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/60150e7b-665a-49a2-8e2e-2097986142f3
Another option is create two structs and use an appropriate cast once you know which type it is.
hth
Mario
In C++, we know that all members of UNION shared the same memory chunk and can only have one member of an object at a time.
In order to implement this in C#, we need to use the LayoutKind to Explicit and set all the starting point of each member to 0.
In my previous example, An error message is displayed stating that the offset of an object type is incorrectly aligned or overlapped by a non-object type.
Answer is we cannot set all the members to FieldOffSet to 0 since it is not allowed to combine the reference type with the value type.
- Thanks to the explanation of Hans Passant
What I did is to create a copy of the UNION Member Structs and change the type of all the String Member Variables to bytes.
I used bytes since this is a value type so I can put this struct into FieldOffSet(0).
Take note, i adjust the FieldOffSet of the next member variable so i can still get the same size of my string variable.
And also for the struct size since i have byte member at the last.
Thanks to Akash Kava and Mario The Spoon for giving me an idea and providing me a useful link.
After calling the function in the DLL and passed this Struct Obj (ref m_objMsg) as a paramter, I need to extract the values.
One way is to have a pointer that points to the address of the struct in the unmanaged memory and convert this pointer a new
Struct with the corresponding member variables (my original structs).
NEW STRUCTS (BYTES)
////////////////////////////////////////////////////////////////
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Size = 31)]
public struct ConxReq
{
[FieldOffSet(0)]
public byteSubsId;
[FieldOffSet(15)]
public Int32 Level;
[FieldOffSet(19)]
public byte Options;
}
[StructLayout(LayoutKind.Explicit, Size = 4)]
public struct ConxNack
{
[FieldOffSet(0)]
public int nReason;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Size = 25)]
public struct StartReq
{
[FieldOffSet(0)]
public byte MsgId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
protected struct Msg
{
public int Length;
public Int16 Type;
public Data MsgData;
}
StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct Data
{
[FieldOffset(0)]
public ConxReq oConxReq;
[FieldOffset(0)]
public ConxNack oConxNack;
[FieldOffset(0)]
public StartReq oStartReq;
}
////////////////////////////////////////////////////////////////
MY ORIGINAL STRUCTS
////////////////////////////////////////////////////////////////
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyConxReq
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string SubsId;
public Int32 Level;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
public string Options;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStartReq
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 25)]
public string MsgId;
}
[StructLayout(LayoutKind.Sequential)]
public struct MyConxNack
{
public int nReason;
}
///////////////////////////////////////////////////////////////
Since I have a Msg.Type, i know what kind of struct (type) I could cast the object.
Like for example
ReceiveMessage(m_Session, nTimeOut, ref oMsg);
switch (oMsg.Type)
{
case 0: // ConxReq
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(oMsg.MsgData.ConxReq); // use the new struct (bytes)
Marshal.StructureToPtr(oMsg.MsgData.ConxReq, ptr, false);
MyConxReq oMyConxReq = new MyConxReq;
oMyConxReq = (MyConxReq) Marshal.PtrToStructure(ptr, typeof(MyConxReq)); // convert it to the original struct
Marshal.FreeHGlobal(ptr);
Then you can use now the oMyConxReq object to acccess the member variables directly.
Please let me know if you have other or better way to do this...
Kindly advise if what I did is correct or if I missed something.
Thank you so much!!! :)
You have to use StructLayout(LayoutKind.Explicit) and FieldOffsets to make union.

calling unmanaged function char returns char *

I have a function in unmanaged C/C++ code (dll) that returns a structure containing a char array. I created C# struct to receive this return value uppon calling the function. And uppon calling this function i get 'System.Runtime.InteropServices.MarshalDirectiveException'
This is C declaration:
typedef struct T_SAMPLE_STRUCT {
int num;
char text[20];
} SAMPLE_STRUCT;
SAMPLE_STRUCT sampleFunction( SAMPLE_STRUCT ss );
This is C# declaration:
struct SAMPLE_STRUCT
{
public int num;
public string text;
}
class Dllwrapper
{
[DllImport("samplecdll.dll")]
public static extern SAMPLE_STRUCT sampleFunction(SAMPLE_STRUCT ss);
}
I am using 1-byte ASCII.
Does anyone has a hint or a solution on how to do this?
The trick to converting a C array member is to use the MarshalAs(UnmanagedType.ByValTStr). This can be used to tell the CLR to marshal the array as an inlined member vs. a normal non-inlined array. Try the following signature.
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct T_SAMPLE_STRUCT {
/// int
public int num;
/// char[20]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=20)]
public string text;
}
public partial class NativeMethods {
/// Return Type: SAMPLE_STRUCT->T_SAMPLE_STRUCT
///ss: SAMPLE_STRUCT->T_SAMPLE_STRUCT
[System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="sampleFunction")]
public static extern T_SAMPLE_STRUCT sampleFunction(T_SAMPLE_STRUCT ss) ;
}
This signature is brought to you by the PInovke Interop Assistant (link) available on CodePlex. It can automatically translate most PInvoke signatures from native code to C# or VB.Net.
This is not an easy structure for P/Invoke to marshal: it's easier to marshal structures that contain char* instead of char[] (although you're then left with the problem of allocating the char* from unmanaged code and later freeing it from managed code).
Assuming you're sticking with the current design, one option is to declare the string array as:
public fixed char text[20];
Unfortunately you must then add the unsafe keyword to any code that accesses this array.
Struct definition in C:
#pragma pack(push, 1)
typedef struct T_SAMPLE_STRUCT {
int num;
char text[20];
};
#pragma pack(pop)
Definition in C#:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct T_SAMPLE_STRUCT
{
[MarshalAs(UnmanagedType.I4)]
public int num;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string text;
}
I have managed to do this by separating function to:
void receiveStruct( SAMPLE_STRUCT ss )
void returnStruct(SAMPLE_STRUCT &ss)
I have changed struct definition as JaredPar told me:
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct T_SAMPLE_STRUCT
{
/// int
public int num;
/// char[20]
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 20)]
public string text;
}
And now it works.
Thanks!
As an interesting aside, since you already have the answer, the basic issue here is that the struct just needs to be the right size. Since managed types don't have inline arrays, you just have to make up the space that it would otherwise need. When you write in C++/CLI, you'll often see the StructLayoutAttribute with an explicit Size parameter. This makes the runtime allocate the right amount of memory for the type, which allows it to be blittable to the native side. It follows that these should work, as well:
[StructLayout(LayoutKind.Sequential, Size=24)]
public struct T_SAMPLE_STRUCT
{
public int num;
// to get the string here, you'd need to get a pointer
public char firstChar;
}
// or
[StructLayout(LayoutKind.Sequential)]
public struct T_SAMPLE_STRUCT
{
public int num;
public byte c0;
public byte c1;
public byte c2;
public byte c3;
public byte c4;
public byte c5;
public byte c6;
public byte c7;
public byte c8;
public byte c9;
public byte c10;
public byte c11;
public byte c12;
public byte c13;
public byte c14;
public byte c15;
public byte c16;
public byte c17;
public byte c18;
public byte c19;
}
Of course, these are much harder to use from managed code (you'd need to copy memory or use pointers), but they illustrate the concept of a blittable type, which is primarily how types are passed between native and managed code.
First you have to put
StructLayout[Sequential] attribute on your struct and I think it will work
[ StructLayout( LayoutKind.Sequential, CharSet=CharSet.Ansi )]
struct SAMPLE_STRUCT
{
public int num;
[ MarshalAs( UnmanagedType.ByValArray, SizeConst=20 )]
public char[] text;
}

Categories

Resources