How to initiate a C struct that includes a pointer from zig

I’m sorry for the bold font here below but I couldn’t understand how to get rid of it.

I want zig to import a C file and let zig compile it for me. The C file also include a .h file that defines a struct. I have simplified my real files here but the problem is the same.
----------------------------------simple.h------------------------

struct simple
{
    unsigned long* ptr_to_val;
};

unsigned long add_value( struct simple *s_ptr );

----------------------------------simple.c------------------------------------------

#include "simple.h"

unsigned long add_value( struct simple *s_ptr )
{
    return *(s_ptr->ptr_to_val) + 1;
}

I want to call add_value() from zig with a legal value of s_ptr->ptr_to_val .
I declare my struct variable in the test part in main.zig like this.
-------------------------------------------------main.zig-----------------------------

const test_file = @cImport(
{
   @cInclude("simple.c");
});

test "simple test" {
   var ret: c_ulong = undefined;
   var st = test_file.simple{.dummy = 2, .ptr_to_val = undefined};

  // How to give the st.ptr_to_val a value that I can use when calling add_test() ? 
   ret = test_file.add_value(st.ptr_to_val)
}

1 Like

.ptr_to_val = &ret should work. And of course you should initialize ret to some value before you call the the C function.

Oh and also, it is generally a bad idea to @cInclude non-header files.
The zig internal parser/translator for C files which gets invoked on @cImport has sometimes trouble translating more complex implementations.
Instead the recommended way is to add C source files to the build.zig using exe.addCSourceFile and only @cInclude the header files.

1 Like

Thanks for the hint to not use @cInclude non header files, I will try that.
Shouldn’t the

var st = test_file.simple{.dummy = 2, .ptr_to_val = undefined}

assign an address to the pointer? And what the pointer is pointed to is undefined. That was my intention anyway.

Using undefined means that you make a promise to the zig compiler that you are going to set the value somehow later.
Zig compiler can put nothing (leave it uninitialized) or might set it to alternating 0 and 1 bits (0xAA bytes) in debug mode.
See: undefined in Zig Language Reference