Created
September 16, 2018 14:54
-
-
Save winksaville/62169f69d8b7f38d505aa2cc866ba6f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//$ zig test opaquetype.zig | |
//opaquetype.zig:8:30: error: parameter of type '(anonymous opaque at opaquetype.zig:12:30)' not allowed | |
// fn getValue(pOpaqueSelf: @OpaqueType()) u32 { | |
// ^ | |
const assert = @import("std").debug.assert; | |
const S = struct { | |
const Self = @This(); | |
value: u32, | |
fn getValue(pOpaqueSelf: @OpaqueType()) u32 { | |
pSelf = @ptrCast(*Self, pOpaqueSelf); | |
return pSelf.value; | |
} | |
}; | |
test "opaquetype" { | |
var s = S { | |
.value = 1, | |
}; | |
var pS = &s; | |
assert(pS.value == 1); | |
assert(pS.getValue() == 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Below is something I got working with help from Andrew and MajorLag.
My first mistake was getValue parameter
pOpaqueSelf
needed to be a pointer;pOpaqueSelf: *@OpaqueType
. But that stilldidn't work, there was still an error as the types didn't match because the call site of getValue had it's own
@OpaqueType
and apparentlythe location is part of the type. So I had to have a single defintion for the type, but that also didn't work because @ptrCast forces
an alignment. So I finally created
fn OpaquePtr
which returns a pointer with proper alignment and is an@OpaqueType
. And thenuse that when defining
fn getValue(pOpaqueSelf: OpaquePtr()) u32
and also when calling getValue;assert(S.getValue(@ptrCast(S.OpaquePtr(), pS)) == 1);
An interesting note: when an
@OpaqueType()
is used with extern C code@ptrCast
at the call site isn't needed.And example is that
pthread_t = @OpaqueType()
andThread.Handle = c.pthread_t
. There are then two call siteswhich pass thread_ptr.data.handle, a call to c.pthread_create and posix.close in std/os/index.zig. Neither of these need @ptrCasts.
But when using @OpaqueType with zig it seems to require @ptrCast as can be seen below:
Here is the full code that "works":