将带有结构字段的结构从C 返回到C#PINVOKE
Return a struct with struct field from c++ to c# pinvoke
我正在尝试从我的本机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();
相关文章:
- 奇怪的结构&GCC&clang(void*返回类型)
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 将大括号括起来的初始值设定项列表作为结构返回
- 从返回的顶点缓冲区查询顶点结构
- 通过 NIF 从C++返回自定义数据结构
- 在类中返回结构时出现问题
- 为什么我们使用在C++中返回数据结构的函数?
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 在 C 函数中返回结构会导致分段错误
- 如何实现返回受保护结构的私有函数
- 如何防止引用返回的私有结构的突变
- 在Cython中定义C 结构返回类型
- MEMCMP以相同(零值)位字段结构返回非零
- 错误:"运算符="不匹配 |结构返回类型
- C 结构返回真实,但是为什么
- C++使用结构返回多个值
- 操作员重新分配功能/结构返回什么
- 使用用户输入来从一个结构返回多个值
- 将结构返回为空
- C++ 从 vector 获取结构 &返回指向非初始化结构的指针