-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d1756b0
commit e01762e
Showing
3 changed files
with
29 additions
and
0 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
func reinterpretPtr*[T: ptr](src: ptr or pointer): T = | ||
## Reinterpret the given pointer to a different pointer type. | ||
## | ||
## This is same to cast, but only accepts a pointer type for safer type convertion. | ||
## But it still can be unsafe. | ||
cast[T](src) | ||
|
||
when isMainModule: | ||
var | ||
a = 123 | ||
pa = a.addr | ||
pa2: pointer = pa | ||
|
||
doAssert reinterpretPtr[ptr int](pa2) is ptr int | ||
doAssert reinterpretPtr[ptr int](pa2)[] == 123 | ||
doAssert not compiles(reinterpretPtr[ptr int](a)) | ||
doAssert reinterpretPtr[ptr int](nil) is ptr int | ||
doAssert reinterpretPtr[ptr int](nil) == nil | ||
|
||
var | ||
s = "Hello" | ||
cs = s.cstring | ||
ps: pointer = cs | ||
doAssert reinterpretPtr[cstring](ps) is cstring | ||
doAssert reinterpretPtr[cstring](ps) == "Hello" |