[英]Passing Structure from C# to C++
我在C ++中有以下結構:
extern "C" __declspec(dllexport) struct SnapRoundingOption
{
double PixelSize;
bool IsISR;
bool IsOutputInteger;
int KdTrees;
};
這是我在C ++中的函數聲明:
extern "C" __declspec(dllexport) void FaceGenerationDummy(SnapRoundingOption snapOption);
這是相應的C#代碼:
// I also tried not specifying Pack, but the same error occurred.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SnapRoundingOption
{
public double PixelSize;
public bool IsISR;
public bool IsOutputInteger;
public int KdTrees;
public SnapRoundingOption(double pixelSize, bool isISR, bool isOutputInt, int kdTrees)
{
PixelSize = pixelSize;
IsISR = isISR;
IsOutputInteger = isOutputInt;
KdTrees = kdTrees;
}
}
[DllImport("Face.dll")]
public static extern void FaceGenerationDummy(SnapRoundingOption snapRoundingOption);
但是,當我使用此測試調用FaceGenerationDummy
時:
[Test]
public void DummyTest()
{
SimpleInterop.FaceGenerationDummy(new SnapRoundingOption(10, true, false, 1));
}
我發現KdTrees在C ++中為0,而不是傳入的1。
我究竟做錯了什么?
編輯1:我在Windows 7 32位上使用Visual Studio 2008。
編輯2: sizeof(SnapRoundingOption)
返回相同的數字 - 16。
這里的問題是你如何編組bool
字段。 這些是C ++中的單個字節,因此需要進行編組,以便:
[StructLayout(LayoutKind.Sequential)]
public struct SnapRoundingOption
{
public double PixelSize;
[MarshalAs(UnmanagedType.U1)]
public bool IsISR;
[MarshalAs(UnmanagedType.U1)]
public bool IsOutputInteger;
public int KdTrees;
}
在C ++方面匹配這個:
struct SnapRoundingOption
{
double PixelSize;
bool IsISR;
bool IsOutputInteger;
int KdTrees;
};
我刪除了包裝設置,以便結構對齊平台自然。
您還應該確保您的呼叫約定一致。 看起來它看起來像C ++代碼使用cdecl
,而C#代碼使用stdcall
。 例如
[DllImport("Face.dll", CallingConvention=CallingConvention.Cdecl)]
將對齊界面的兩側。
bool
是不可憐的 ! 它的默認編組是Win32 BOOL
(4個字節), 而不是 bool
(1個字節)!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.