So I'm trying to learn macros, and its not easy if you've never done
metaprogramming. Anyway, I'm trying to write a wrapper for a C function that
takes a variable number of arguments, with the first being a string that
specifies the types of the rest. I want the wrapper to create this string
automatically. What I have implemented so far works as far as I can tell. But
now I'm wondering:
* Did I make any stupid mistakes?
* Could I have done this using `quote` and it would have been nicer?
import macros
# cfunc expects a variable numebr of arguments, with first being a string
that specifies types of the following args, e.g.
# cfunc("isis", 5, "foo", 7, "bar")
proc cfunc(bla: varargs[string, `$`]): string =
for s in items(bla):
result.add s
# wrapper without the first argument
macro wrapper(args: varargs[typed]): untyped =
var params = @[newLit("")]
var typestring = ""
for s in args:
case typeKind(getType(s)):
of ntyString: typestring.add("s")
of ntyInt: typestring.add("i")
else: discard
params.add(s)
params[0].strVal = typestring
result = newCall("cfunc", params)
# "tests"
echo wrapper(5, 7, "bar")
let
x = 4
y = 8
z = "bar"
echo wrapper(x, y, z, y)
Run