How to assign and print char * from C

Zig has quickly become one of my favorite languages (probably my favorite). But I am a little hung up on learning C interop. Here is the quick exercise I’m trying to do.

#ifndef PERSON_H
#define PERSON_H

typedef struct {
   int age;
   char* name;
} person_t;

#endif //PERSON_H
const std = @import("std");
const c = @cImport({
    @cInclude("person.h");
});

const Person = extern struct {
    age: c_int,
    name: *const ?[*:0]u8,
};

pub fn main() void {
    var person: Person = undefined;
    person.age = 24;
    person.name = @ptrCast(@alignCast("coredump"));
    // const name = std.mem.span(person.name);
    std.debug.print("name: {d}\nage: {d}\n", .{ person.name, person.age });
    // std.debug.print("name: {s}\n", .{name});
}

I get the memory address when I try to print person.name.

name: ?[*:0]u8@10dff98
age: 24

I saw someone with a similar issue on here while trying to use GLFW, and it was advised to use std.mem.span(), but I get either an error saying invalid type given to std.mem.span: const ?[:0]u8 or if I pass it in with a dereference pointer I get a runtime error:

General protection exception (no address available)
/usr/lib64/zig/9999/lib/std/mem.zig:1060:48: 0x10789d8 in indexOfSentinel__anon_7829 (main)
                    const block: Block = p[i..][0..block_len].*;
                                               ^
/usr/lib64/zig/9999/lib/std/mem.zig:1012:39: 0x1068d7f in len__anon_7279 (main)
                return indexOfSentinel(info.child, sentinel, value);
                                      ^
/usr/lib64/zig/9999/lib/std/mem.zig:789:18: 0x1034cf1 in span__anon_4104 (main)
    const l = len(ptr);
                 ^
/usr/lib64/zig/9999/lib/std/mem.zig:783:24: 0x1032fe2 in span__anon_3679 (main)
            return span(non_null);
                       ^
/home/wizard/fun/zig/learn/interop/main.zig:15:30: 0x1031f7d in main (main)
    const name = std.mem.span(person.name.*);
                             ^

using 0.13.0-dev.75+5c9eb4081
Any Zig extraordinaires out there that can help me solve this brain buster?
Thanks!

const std = @import("std");
const c = @cImport({
    @cInclude("person.h");
});

// const Person = extern struct {
//     age: c_int,
//     name: *const ?[*:0]u8,
// };

pub fn main() void {
    var person: c.person_t = undefined;
    person.age = 24;
    // person.name = @ptrCast(@alignCast("coredump"));
    person.name = @constCast("coredump");
    std.debug.print("name: {s}\nage: {d}\n", .{ person.name, person.age });
}

huge misunderstanding on how @cImport works

name: coredump
age: 24

Thank you everyone for listening to me talk to myself.

4 Likes