引用外部函数传递的结构具有未设置的字段

问题描述 投票:0回答:0

c 标题摘录:

struct GetArgvOptions {
  uint      skip;
  pid_t     pid;
  bool      nuls;
};
bool get_argv_of_pid(const struct GetArgvOptions* options, struct ArgvResult* result);

c# 类库提取:

[StructLayout(LayoutKind.Sequential)]
struct GetArgvOptions {
    public nuint skip;
    public nint  pid;
    public bool  nuls;
}
[DllImport("libgetargv.dylib", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
static extern bool get_argv_of_pid(in GetArgvOptions options, out ArgvResult result);

c# 单元测试摘录:

int pid = Environment.ProcessId;
GetArgvOptions opt;
opt.pid = pid;
opt.skip = 0;
opt.nuls = false;
Console.WriteLine($"pid: {opt.pid}");
ArgvResult res = new ArgvResult();
bool success = get_argv_of_pid(in opt, out res);

get_argv_of_pid
函数看到一个 pid 设置为 0 而不是实际 pid 的选项结构,打印到控制台的行确认在将结构传递给函数之前设置了 pid。

c# c struct pinvoke ref
© www.soinside.com 2019 - 2024. All rights reserved.