Skip to content

Commit

Permalink
Nim manual: better byref pragma explanation (#23192)
Browse files Browse the repository at this point in the history
Nim manual says:
> When using the Cpp backend, params marked as byref will translate to
cpp references `&`

But how `byref` pragma translate to depends on whether it is used with
`importc` or `importcpp`.
When `byref` pragma used with `importc` types and compiled with the Cpp
backend, it is not traslated to cpp reference `&`.

---------

Co-authored-by: Andreas Rumpf <[email protected]>
  • Loading branch information
demotomohiro and Araq authored Jan 9, 2024
1 parent 8d1c722 commit e20a2b1
Showing 1 changed file with 56 additions and 2 deletions.
58 changes: 56 additions & 2 deletions doc/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -8573,8 +8573,62 @@ Byref pragma
The `byref` pragma can be applied to an object or tuple type or a proc param.
When applied to a type it instructs the compiler to pass the type by reference
(hidden pointer) to procs. When applied to a param it will take precedence, even
if the the type was marked as `bycopy`. When using the Cpp backend, params marked
as byref will translate to cpp references `&`.
if the the type was marked as `bycopy`. When an `importc` type has a `byref` pragma or
parameters are marked as `byref` in an `importc` proc, these params translate to pointers.
When an `importcpp` type has a `byref` pragma, these params translate to
C++ references `&`.

```Nim
{.emit: """/*TYPESECTION*/
typedef struct {
int x;
} CStruct;
""".}
{.emit: """
#ifdef __cplusplus
extern "C"
#endif
int takesCStruct(CStruct* x) {
return x->x;
}
""".}
type
CStruct {.importc, byref.} = object
x: cint
proc takesCStruct(x: CStruct): cint {.importc.}
```

or


```Nim
type
CStruct {.importc.} = object
x: cint
proc takesCStruct(x {.byref.}: CStruct): cint {.importc.}
```

```Nim
{.emit: """/*TYPESECTION*/
struct CppStruct {
int x;
int takesCppStruct(CppStruct& y) {
return x + y.x;
}
};
""".}
type
CppStruct {.importcpp, byref.} = object
x: cint
proc takesCppStruct(x, y: CppStruct): cint {.importcpp.}
```

Varargs pragma
--------------
Expand Down

0 comments on commit e20a2b1

Please sign in to comment.