将带有结构字段的结构从C 返回到C#PINVOKE

Return a struct with struct field from c++ to c# pinvoke

本文关键字:结构 返回 C#PINVOKE 字段      更新时间:2023-10-16

我正在尝试从我的本机C 代码返回带有其他结构字段的结构,但有错误:方法的类型签名不兼容。

这是我的C 代码:

namespace path
{
struct Vector3
{
public:
    float x;
    float y;
    float z;
};
struct PointState
{
public:
    Vector3 position_;
    bool reformation;
};
}

在这里我的API功能:

extern "C"
{
PATHFINDER_API void SetupGraph(const char * json);
PATHFINDER_API path::Vector3 CheckReturn();
PATHFINDER_API path::PointState CheckStruct();
}

这是我的C#结构代码:

 [StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
    public float x;
    public float y;
    public float z;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct PointState
{
    [MarshalAs(UnmanagedType.LPStruct)]
    public Vector3 position_;
    public bool reformation;
};

和pinvoke dllimport:

        [DllImport("path", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false, EntryPoint = "CheckStruct")]
    private static extern PointState CheckStruct();
    public PointState CheckReturn2()
    {
        return CheckStruct();
    }

请问,我在做什么错?我自己找不到答案。

您的代码有一些问题:

  • 您在嵌套结构上使用了[MarshalAs(UnmanagedType.LPStruct)],但这完全是错误的。该领域不是指针。该属性应删除。
  • bool类型不能以返回值进行编组。您可以用byte替换C#bool来解决该问题,然后将值与零进行比较。
  • 此外,您添加的某些属性似乎是不必要的。我怀疑您做了一个通常尝试随机尝试进行很多更改的事情,但是将它们留在您在此处发布的代码中。

我会使用以下声明:

[StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
    public float x;
    public float y;
    public float z;
};
[StructLayout(LayoutKind.Sequential)]
public struct PointState
{
    public Vector3 position_;
    private byte _reformation;
    public bool reformation { get { return _reformation != 0; } }
};
[DllImport("path", CallingConvention = CallingConvention.Cdecl)]
private static extern PointState CheckStruct();