Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Structs mapped from C header need completeStruct pragma, otherwise sizeof doesn't work on those #276

Open
kaushalmodi opened this issue May 4, 2021 · 0 comments

Comments

@kaushalmodi
Copy link

kaushalmodi commented May 4, 2021

Hello,

I recently came across one Nim object mapped to a C struct using nimterop that caused compilation failure only when I used sizeof to calculate the size of that struct.

Here's the relevant snippet from svdpi.h:

typedef struct t_vpi_vecval {
uint32_t aval;
uint32_t bval;
} s_vpi_vecval, *p_vpi_vecval;

typedef s_vpi_vecval svLogicVecVal;

Here's what Nimterop parses that to:

  t_vpi_vecval* {.bycopy, impsvdpiHdr, importc: "struct t_vpi_vecval".} = object
    aval*: uint32
    bval*: uint32

  s_vpi_vecval* {.importc, impsvdpiHdr.} = t_vpi_vecval
  p_vpi_vecval* {.importc, impsvdpiHdr.} = ptr t_vpi_vecval
  svLogicVecVal* {.importc, impsvdpiHdr.} = s_vpi_vecval

The code is functionally correct. But when I use sizeof on an object of type svLogicVecVal, I get:

9.struct_arrays/libdpi.nim(29, 24) Error: 'sizeof' requires '.importc' types to be '.completeStruct'

Looking around on Nim Forum, I found this post by @timotheecour and that helped!

I then put this in svdpi.nim, with the completeStruct pragma and everything worked:

cOverride:
  type
    t_vpi_vecval* {.bycopy, impsvdpiHdr, importc: "struct t_vpi_vecval", completeStruct.} = object
      aval*: uint32
      bval*: uint32
    s_vpi_vecval* {.importc, impsvdpiHdr, completeStruct.} = t_vpi_vecval
    svLogicVecVal* {.importc, impsvdpiHdr, completeStruct.} = s_vpi_vecval

cImport(cSearchPath("svdpi.h"), recurse = true, flags = "-f:ast2")

I don't completely understand why that pragma is needed in the first place.

Should nimterop be adding the completeStruct pragma automatically?


Reference code


Versions

  • nim 1.4.6+
  • nimterop 0.6.13
kaushalmodi added a commit to kaushalmodi/nim-svdpi that referenced this issue May 4, 2021
- Bump nim dependency because completeStruct pragma is not available
  on nim 1.2.x and older versions.

Ref: nimterop/nimterop#276
kaushalmodi added a commit to kaushalmodi/nim-svdpi that referenced this issue Sep 6, 2022
This resolves the sizeof issue seen in
nimterop/nimterop#276 and also makes the
code compile with latest Nim devel version 1.7.1 as of today.
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

No branches or pull requests

1 participant