6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nimでポインタ操作

Posted at

はじめに

Nimだけでコーディングしていると、ポインタってあんま使わないような気がするけど、
C言語のライブラリとか使おうとすると配列のポインタとか返すやつがいるので、
ポインタ操作が必要になってくる。

ポインタ型は演算できない

C言語だと++とかでポインタを進められるけどNimだと演算できない

type pair = (int, int)
var array = [(1, 2), (3, 4), (5, 6)]
let array_ptr = array.addr
let new_ptr = array_ptr + 1   
Error: type mismatch: got <ptr array[0..2, tuple of (int, int)], int literal(1)

ポインタはuintにcastして計算する。

こんな感じ

type pair = (int, int)                                                                                                       
var array = [(1, 2), (3, 4), (5, 6)]                                                                                         
let array_ptr = array.addr                                                                                                   
for i in 0..array.len-1:                                                                                                     
  echo cast[ptr pair](cast[uint](array_ptr) + uint(sizeof(pair) * i))[]
実行結果
(1, 2)
(3, 4)
(5, 6)

関数化

こんな感じのジェネリクス関数を定義しておくと便利かもしれない

proc `[]`[T](p: ptr T, index: int): T =                                                                                      
  cast[ptr T](cast[uint](p) + sizeof(T)*index)[]                                                                             
                                                                                                                             
var array = [(1, 2), (3, 4), (5, 6)]
let array_ptr = array.addr                                                                                                   
for i in 0..array.len-1:                                                                                                     
  echo array_ptr[i]    

以上〜。

6
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?