Hi all,
I am trying to use a C++ library by creating C++ code dynamically (i.e. meta-programming C++). I’m using Cxx package for this.
In Cxx there’s a macro-string named icxx_str which basically wraps the code inside the argument string in a C++ function and executes it.
It looks like this (source code):
macro icxx_str(str, args...)
annotations = length(args) > 0 ? first(args) : ""
esc(process_cxx_string(str, false, false, __source__, annotations))
end
A simple usage:
# cxx is for global scope
cxx"include <iostream>;"
# icxx can interpolate variables
a_variable = "hello, world!"
icxx"std::cout << $a_variable << std::endl;"
I am creating the code dynamically, e.g.
function test()
a_variable = [4, 5]
namespace = "std"
cppcode = "$namespace::cout << \$(conversion_fn(a_variable)) << $namespace.endl;"
end
Here, cppcode is a string where some variables are interpolated ($namespace), while other variables (conversion_fn(a_variable)) are meant to be passed as arguments and thus should be interpolated by icxx_str, which also takes care of proper type conversion. conversion_fn takes care of converting Vector{Int64} to a type that icxx knows how to convert (namely: cxxt"std::vector<double>")
Now, I need to put variable cppcode as argument to icxx_str; however, if I do @icxx_str(cppcode) it obviously tries to use "cppcode" as string.
Thanks to the Slack chat, I came up with @eval @icxx_str($cppcode), which works if there are no local variables that must be interpolated by icxx_str, because @eval works in the global scope. Indeed, it works in the REPL, but not in a function!
How can I do?