[英]Converting c++ struct to c# and using it?
我有一個C ++結構如下:
struct Vehicle
{
u32 something;
Info *info;
u8 something2[ 0x14 ];
Vector3f location;
Template* data;
};
struct Info
{
u32 speed;
std::string name;
BuffCollection** buffCollection;
void* sectionPtr;
};
struct Template
{
u32 templateID;
};
從這個問題中 ,我弄清楚了u32,u8等的含義,或者我認為是的。
然后我嘗試用它制作自己的C#結構:
[StructLayout(LayoutKind.Sequential)]
public struct Vehicle
{
public uint Something;
public Info Info;
public byte Something2;
public Vector3f Location;
public Template Data;
}
[StructLayout(LayoutKind.Sequential)]
public struct Info
{
public uint Speed;
public string Name;
public byte[] BuffCollection;
public IntPtr SectionPointer;
}
[StructLayout(LayoutKind.Sequential)]
public struct Template
{
public uint TemplateId;
}
public struct Vector3f
{
public float X, Y, Z;
public Vector3f(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
}
但是,當我嘗試閱讀車輛時:
[DllImport("Core.dll")]
static extern Vehicle GetVehicle();
static void Main()
{
var vehicle = GetVehicle();
Console.WriteLine(vehicle.Info.Name);
Console.ReadKey();
}
我收到以下錯誤:
System.Runtime.InteropServices.MarshalDirectiveException: Method's type signature is not PInvoke compatible
通過對它的搜索,它使我相信我的結構轉換是錯誤的。
關於結構:
Vehicle.Info
是指針,因此您需要將其聲明為IntPtr Info
,然后使用Marshal.PtrToStructure / Marshal.StructureToPtr
在托管代碼中讀取/寫入其值;
Vehicle.something2
是一個字節數組,而不是一個字節,因此您需要這樣聲明:
[MarshalAs(UnmanagedType.ByValArray,SizeConst = 20)]
byte [] something2 =新的byte [20];
Vehicle.Data
參見#1,同樣的問題
Info.Name
不提供std :: string的編組,因此您將需要編寫自己的封送程序(請參閱: 使用std :: string的PInvoke的自定義封送程序)或將類型更改為char *您的c ++庫。 Info.BuffCollection
也應該是IntPtr或BuffCollection [](取決於BuffCollection類型的含義-您的問題中未提供) 關於GetVehicle();
的簽名和調用GetVehicle();
方法:
該方法很可能返回指向結構的指針,而不是結構本身(只是推測,請仔細檢查)。 如果是這樣,則需要將其聲明為
static extern IntPtr GetVehicle();
然后使用Marshal.PtrToStructure
將其轉換為您的結構,如下所示:
var vehiclePtr=GetVehicle();
var vehicle = (Vehicle)Marshal.PtrToStructure(vehiclePtr, typeof(Vehicle));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.