Linux 上的 .NET Core - 元帅结构
.NET Core on Linux - Marshal structures
我有一个.NET Core控制台应用程序,可以从C++库中调用一些函数。我试图调用的函数 simpty 在某些settings
中获取并将结果输出到result
中。
C++:
struct settings
{
char* input_path;
char* first_file;
char* second_file;
char* mask;
char* log_path;
int count_accepted;
double confidence;
char* device;
};
struct result
{
int count;
foo* foos;
bool is_preprocessed;
double duration;
};
bool process_input(const settings& settings, result* result);
C#:
[StructLayout(LayoutKind.Sequential)]
public struct Settings
{
[MarshalAs(UnmanagedType.LPStr)]
public string input_path;
[MarshalAs(UnmanagedType.LPStr)]
public string first_file;
[MarshalAs(UnmanagedType.LPStr)]
public string second_file;
[MarshalAs(UnmanagedType.LPStr)]
public string mask;
[MarshalAs(UnmanagedType.LPStr)]
public string log_path;
[MarshalAs(UnmanagedType.I4)]
public int count_accepted;
[MarshalAs(UnmanagedType.R8)]
public double confidence;
[MarshalAs(UnmanagedType.LPStr)]
public string device;
}
[StructLayout(LayoutKind.Sequential)]
public struct Result
{
[MarshalAs(UnmanagedType.I4)]
public int count;
[MarshalAs(UnmanagedType.SysInt)]
public IntPtr foos;
[MarshalAs(UnmanagedType.I1)]
public bool is_preprocessed;
[MarshalAs(UnmanagedType.R8)]
public double duration;
}
[DllImport("myLib", EntryPoint = "process_input", CallingConvention = CallingConvention.Cdecl)]
[return:MarshalAs(UnmanagedType.I1)]
public static extern bool ProcessInput(Settings settings, out Result result);
这一切都在Windows上运行良好,但在Linux上不起作用。当我在C++面(从process_input
(打印设置时,我在 int 和 double 属性中得到完全不同的值,并且在尝试访问 char* 属性时出现分段错误。
我还尝试从C++代码(Windows和Linux(调用此库,它按预期工作。据我了解,这是一个编组问题,但我自己无法确定。我是一名 C# 开发人员,对 C++、PInvoke 或 Linux 没有太多经验。
我使用Windows 10(x64(和Ubuntu 16.04(x64(。
正如David Heffernan在评论中建议的那样,我添加了一个明确的ref
关键字,它起作用了。
这是我之前的函数签名:
public static extern bool ProcessInput(Settings settings, out Result result);
之后:
public static extern bool ProcessInput(ref Settings settings, out Result result);
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 将结构数组从 C#(.NET Core) 传递到 C++(unamnaged)
- Linux 上的 .NET Core - 元帅结构