Skip to content

Conversation

@timotheecour
Copy link
Member

@timotheecour timotheecour commented Dec 6, 2019

/cc @Araq

before PR:
Error: unhandled exception: intVal [FieldError]
whenever setting a ptr or pointer field (assigning a ptr variable at CT already works)

after PR:
setting a ptr or pointer field works

examples

there are many use cases, here's a simple one (example1 with pointer field) and a more elaborate one (example2 with ptr field)
example below requires building nim with -d:nimHasLibFFI and compiling with --experimental:compiletimeFFI for importc at CT

nim c -d:timn_D20191206T095533 --app:lib --outdir:$build_D/lib/ t0816b.nim # only needed for example2
nim c -r --experimental:compiletimeFFI t0816.nim 

t0816.nim:

import system/ansi_c
import ./t0816b

proc c_malloc*(size: csize_t): pointer {.importc: "malloc", header: "<stdlib.h>".}
proc c_fprintf*(f: CFilePtr, frmt: cstring): cint {.importc: "fprintf", header: "<stdio.h>", varargs, discardable.}

type Foo = object
  a: pointer
  b: CFilePtr

proc main()=
  var f: Foo

  ## example 1: pointer
  f.a = c_malloc(1234)

  ## example 2: ptr (CFilePtr = ptr CFile)
  f.b = getStderr()
  # c_fprintf(cstderr, "hello world\n") # doesn't work yet, so we need an intermediate library, see t0816b.nim
  c_fprintf(getStderr(), "hello world 1\n")
  c_fprintf(f.b, "hello world 2\n")
  ## re-assignment works
  f.b = getStdout()
  c_fprintf(f.b, "hello world 3\n")
  ## re-assignment to nil works
  f.b = nil

static: main()
main()

t0816b.nim:

when defined(timn_D20191206T095533):
  {.emit:"""
  #include <stdlib.h>
  #include <stdio.h>
  NIM_EXTERNC
  FILE* getStderr(){ return stderr;}
  FILE* getStdout(){ return stdout;}
  """.}

else:
  from system/ansi_c import CFilePtr
  const libF = "libt0816b.dylib"
  {.push importc, dynlib: libF.}
  proc getStderr*(): CFilePtr
  proc getStdout*(): CFilePtr
  {.pop.}

note

I added a comment regarding nkPtrLit, which is what compiler/evalffi.nim uses:

const
  nkPtrLit = nkIntLit # hopefully we can get rid of this hack soon

ideally, nkPtrLit could be a new member of TNodeKind to avoid conflation; but this could be done in future PR

@timotheecour timotheecour changed the title VM: allow setting ptr fields at CT VM: allow setting ptr/pointer fields at CT Dec 6, 2019
@Araq Araq merged commit 23fc93f into nim-lang:devel Dec 6, 2019
@timotheecour timotheecour deleted the pr_vm_ptr_field_D20191206T095533 branch December 7, 2019 19:14
timotheecour added a commit to timotheecour/Nim that referenced this pull request Dec 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants