简体   繁体   English

将结构从C#传递给C ++

[英]Passing Structure from C# to C++

I have the following structure in C++: 我在C ++中有以下结构:

extern "C" __declspec(dllexport) struct SnapRoundingOption
{
    double PixelSize;
    bool IsISR;
    bool IsOutputInteger;
    int KdTrees;
};

And this is my function declaration in C++: 这是我在C ++中的函数声明:

extern "C" __declspec(dllexport) void FaceGenerationDummy(SnapRoundingOption snapOption);

This is the corresponding C# code: 这是相应的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);

However, when I call the FaceGenerationDummy with this test: 但是,当我使用此测试调用FaceGenerationDummy时:

[Test]
public void DummyTest()
{
    SimpleInterop.FaceGenerationDummy(new SnapRoundingOption(10, true, false, 1));
}

I found that KdTrees is 0 in C++, instead of 1 as passed in. 我发现KdTrees在C ++中为0,而不是传入的1。

What am I doing wrong? 我究竟做错了什么?

Edit 1: I am using Visual Studio 2008 on Windows 7 32-bit. 编辑1:我在Windows 7 32位上使用Visual Studio 2008。

Edit 2: Both sizeof(SnapRoundingOption) return the same number – 16. 编辑2: sizeof(SnapRoundingOption)返回相同的数字 - 16。

The problem here is how you are marshalling the bool fields. 这里的问题是你如何编组bool字段。 These are single bytes in C++ and so need to be marshalled so: 这些是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;
}

Match this up on the C++ side: 在C ++方面匹配这个:

struct SnapRoundingOption
{
    double PixelSize;
    bool IsISR;
    bool IsOutputInteger;
    int KdTrees;
};

I removed the packing settings so that the structures will have alignment natural to the platform. 我删除了包装设置,以便结构对齐平台自然。

You should also make sure that your calling conventions agree. 您还应该确保您的呼叫约定一致。 As it stands it looks like the C++ code uses cdecl , and the C# code uses stdcall . 看起来它看起来像C ++代码使用cdecl ,而C#代码使用stdcall For example 例如

[DllImport("Face.dll", CallingConvention=CallingConvention.Cdecl)]

would align the two sides of the interface. 将对齐界面的两侧。

bool is NOT blittable ! bool可怜的 Its default marshaling is the Win32 BOOL (which is 4 bytes), not bool (which is 1 byte)! 它的默认编组是Win32 BOOL (4个字节), 而不是 bool (1个字节)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM