我有一個C++結構,它具有下面的char [20],並且它被打包。在c#中的char []數組相當於#
#pragma pack(push, temp_aion_packed, 1)
struct temp
{
char x[20];
char y[20];
};
#pragma pack(pop, temp_aion_packed)
現在我怎麼能在c#中寫這個結構,以便兩者都是相同的。我在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;
}
下面
是在C#中進行pinvoke聲明
[DllImport("rmsCAPI.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "OrderRequirement")]
public static extern int OrderRequirement(ref temp tmp);
C++函數調用此結構作爲參數
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);
}
但是當我做這樣的c#它給我的C++垃圾數據,當我在c#中爲他們分配值。任何人都可以協助。
謝謝大家對上述問題的幫助,但現在我得到了一個新的問題,這是一個擴展,我在下面詳細提供了一切。
我在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)
結構我寫等價的C#結構像這樣
[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;
}
下面是我的C#的PInvoke
[DllImport("rmsCAPI.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "OrderRequirement")]
public static extern int OrderRequirement(ref temp tmp);
下面
是我的C++方法調用結構作爲參數
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);
}
現在我得到的問題是我在struct temp中聲明的結構變量m_type(struct「type」),在C++程序中正確打印的聲明之前聲明的變量(long req)在那之後沒有給我任何輸出。所以我認爲在c#中的結構聲明搞亂了,我無法弄清楚,所以任何人都可以幫助。
我想你想要byte [20]。 – Ben
@Ben'byte [20]'不能在C#中編譯。 –
@DavidHeffernan - 我現在詳細提供了一切 – krishna555