簡體   English   中英

如何在 C# 中從 libc 調用 getpwnam()?

[英]How to p/invoke getpwnam() from libc in C#?

讓我們從文檔開始: https : //man7.org/linux/man-pages/man3/getpwnam.3.html

有了這個,我做了以下 C# 代碼:

using System;
using System.Runtime.InteropServices;

if (args.Length < 1) {
    Console.Error.WriteLine("Provide user name.");
    Environment.Exit(-1);
}

var name = args[0];

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
    Syscall.getpwnam(name, out var passwd);
    Console.WriteLine($"User = {name}, UID = {passwd.Uid}, GID = {passwd.Gid}");
    passwd = GetPasswd(name);
    Console.WriteLine($"User = {name}, UID = {passwd.Uid}, GID = {passwd.Gid}");
}
else {
    Console.WriteLine("It supposed to be run on Linux.");
}

static Passwd GetPasswd(string name) {
    var bufsize = 16384;
    var buf = new byte[bufsize];
    var passwd = new Passwd();
    Syscall.getpwnam_r(name, passwd, buf, (uint)bufsize, out var result);
    return result;
}

public struct Passwd {
    public string Name;
    public string Password;
    public uint Uid;
    public uint Gid;
    public string Gecos;
    public string Directory;
    public string Shell;
}

static class Syscall {

    [DllImport("libc", SetLastError = true)]
    public static extern void getpwnam(string name, out Passwd passwd);

    [DllImport("libc", SetLastError = true)]
    public static extern void getpwnam_r(string name, Passwd passwd, byte[] buf, uint bufsize, out Passwd result);

}

它不起作用。

這是我得到的:

User = service, UID = 0, GID = 0
Segmentation fault (core dumped)

我究竟做錯了什么?

我應該如何調用它以獲得實際結構? 我對返回的字符串不感興趣。 我只關心UidGid值。

正如鏈接文檔所提到的 - 此函數接受一個參數 - 名稱,並返回指向帶有數據的結構的指針。 所以簽名應該是:

[DllImport("libc", SetLastError = true)]
public static extern IntPtr getpwnam(string name);

進而:

// we have pointer here
var passwdPtr = Syscall.getpwnam(name);
// don't forget to check if pointer is not IntPtr.Zero.
// interpret data at pointer as structure
var passwd = Marshal.PtrToStructure<Passwd>(passwdPtr);
Console.WriteLine($"User = {passwd.Name}, UID = {passwd.Uid}, GID = {passwd.Gid}");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM