Function pointers: can we create a var function pointer?

I am learning Zig and am trying out the use of function pointers. The following examples work as expected:

    const aFunc = fn (x: i32) void;
    const f: aFunc = theFunc;
    f(3);

    const f_ptr: *const aFunc = &theFunc;
    f_ptr(4);

    var vf_ptr: *const aFunc = undefined;
    vf_ptr = &theFunc;
    vf_ptr(5);

But not this:

    var vf_vptr: *aFunc = undefined;
    // error: expected type '*fn (i32) void', found '*const fn (i32) void'
    vf_vptr = &theFunc;
    vf_vptr(6);

I understand why this is so, but would like to know if one can get a non-constant function pointer and If so, how. I am assuming this should be possible for example to use dynamic libraries, but may not be feasible/possible at runtime via the standard library.

TIA.

Well, what would be the semantics of a non-const function pointer? Would you change it’s assembly code? How would you know when the underlying buffer ends?

To load a dynamic library, you can currently just load the code into a buffer, and then use @ptrCast() to cast it to a function pointer. There is no need to add extra semantics to function pointer types to get this done.

1 Like

@IntegratedQuantum Thanks for the feedback. Please ignore my previous deleted response. After reviewing the meaning of the types I see what you mean. Changing the contents of the pointer is tantamount to injecting code. Not a safe thing to do even though someone may find a legitimate use for it.

It also is not related to the dynamic library issue - one would not (want to) alter the code of the library.

Thanks.