[英]passing a c++ struct to a c# application
我的cpp文件中具有以下結構:
struct EntityData
{
char globalId[512];
int mySpeed;
double x;
double y;
double z;
double h;
double p;
double r;
};
我有一個獲取索引號並返回正確結構的方法:
extern "C" { __declspec(dllexport) getDataStruct(int index)
此方法是公開的,因此我可以在c#應用程序中使用此方法,並且不斷收到錯誤消息:
元帥指令異常。
我的C#代碼:
[DllImport("my64.dll")]
[return: MarshalAs(UnmanagedType.LPStruct)]
public static extern EntityDataRx getDataStruct(int index);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct EntityDataRx
{
[MarshalAs(UnmanagedType.LPStr, SizeConst = 512)]
StringBuilder globalId;
int mySpeed;
double x;
double y;
double z;
double h;
double p;
double r;
}
我想念什么?
在msdn文檔頁面上顯示:
ByValTStr
類型用於出現在結構中的內聯固定長度字符數組。 其他類型適用於包含在包含指向字符串的指針的結構中的字符串引用。
所以從你的結構來看
struct EntityData
{
char globalId[512];
// ...
}
您應該像這樣定義C#結構:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct EntityDataRx
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
char[] globalId;
// ...
}
當您具有“指向以NULL終止的ANSI字符數組的指針”但您擁有的是固定長度的數組時,將使用LPStr
。
終於解決了。 問題是從cpp結構中我返回一個指向該結構的指針:
struct EntityData
{
char globalId[512];
int mySpeed;
double x;
double y;
double z;
double h;
double p;
double r;
};
在我的C#應用程序中:
[DllImport("listenHLA1516e_64.dll")]
//[return: MarshalAs(UnmanagedType.Struct)] **cancelled not necessary**
public static extern IntPtr getDataStruct(int index);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct EntityDataRx
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
char[] globalId;
int mySpeed;
double x;
double y;
double z;
double h;
double p;
double r;
}
IntPtr a = getDataStruct(i);
EntityDataRx ent = (EntityDataRx)Marshal.PtrToStructure(a, typeof(EntityDataRx));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.