Calling user specified R function in inline C++ body - r

I have been working with the R package "RcppArmadillo". I already used it to define two cxxfunction(they have been debugged are fine to use):
calc1 <- cxxfunction(signature(A="integer", B="integer"),...)
calc2 <- cxxfunction(signature(A="integer", K="integer"),...)
Now I'm writing the body part of another cxxfunction main and wish to call calc1 and calc2 within the for loops there, like:
body_main = '
...
for(int i=0; i<N; i++){
// This is where I want to call calc1.
// (?)
for(int j=0; j<N; j++){
// This is where I want to call calc2.
// (?)
}
}
'
Is there anyway that I can achieve that? Can that be done in an inline fashion?
I haven't seen an example of inline usage of RcppArmadillo(or Rcpp, RcppGSL) in which people write a subroutine within the body part - specifically, I mean code looks like this:
body_example = '
// Subroutine
SEXP(/*or something else*/) func_0(SEXP A, SEXP B){
...
return ...;
}
// Then call it from the main part
...
AB = func_0(A, B);
...
'
My question probably looks naive but it haunts me nevertheless. Can anyone help explain this? I'd appreciate that a lot!

You could switch from using cxxfunction() from package inline to using Rcpp attributes and its sourceCpp(). That way you get the predictable function headers at the C++ level, see the Rcpp atributes vignette.
Or split calc1 and calc2 into 'worker' and 'wrapper', have cxxfunction() around the wrapper allowing you to call the worker.
The key issue here really is that cxxfunction() exists to create an R-callable function, and it generates internal randomized function headers.
Lastly, a package would help too.

Related

How to define persistent matrix variable inside the Scilab function?

I have been developing a Scilab function where I need to have persistent variable of the matrix type. Based on my similar question I have chosen the same approach. Below is the code I have used for test of this approach.
function [u] = FuncXYZ(x)
global A;
global init;
if init == 0 then
init = 1;
A = eye(4, 4);
endif
u = A(1, 1);
endfunction
As soon as I have integrated the function inside my Xcos simulation I have been surprised that I see "0" at the output of the scifunc_block_m.
Nevertheless I have found that in case I use below given command for "return" from the function
u = A(3, 3);
the function returns really the expected "1". Additionaly if I take a look at the Variable Browser on the top right corner of the Scilab window I can't se the expected A 4x4 item. It seems that I am doing something wrong.
Can anybody give me an advice how to define a persistent variable of the matrix type inside the Scilab function?
Thanks in advance for any ideas.
Global variables are by default initialized with an empty matrix. Hence, you should detect first call with isempty()
function [u] = FuncXYZ(x)
global A;
global init;
if isempty(init)
init = 1;
A = eye(4, 4);
end
u = A(1, 1);
endfunction
BTW, your code is incorrect, there is no endif in Scilab.

Is there a way of passing an R function object (`CLOSXP`) to C level code and register it as a callback?

Problem
I am wrapping a fraction of the GLFW C library in R.
One functionality I'd like to wrap is the registration of callbacks.
For example, to set an error callback in C, GLFW provides the function:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun callback)
whose callback signature is:
void callback_name(int error_code, const char* description)
Could you provide any pointers on how to allow the user to define a function in R, i.e. a CLOSXP object, and pass it, and, somehow, get it transformed to a C function passable to glfwSetErrorCallback().
I am looking for a plain R's C internal API solution, i.e., and not something based on Rcpp, please.
I have read this blog post , and I got the feeling I could perhaps use some combination of Rf_install() and R_tryEval()... but on the other hand, in Hadley's R internals, I only see Rf_install() associated with symbols (SYMSXP). I could not find much information about Rf_install() either except for some appearances in code snippets in An external pointer example in Writing R Extensions.
Edit
After reading the answer to Calling R from C from R in mcmc, I think might be able to register an R function as a callback if I resort to using a global variable, SEXP rcallback:
R code
#' #export
glfw_set_error_callback <- function(callback) {
.Call("glfw_set_error_callback_", callback)
}
C code
SEXP rcallback;
static void error_cb(int error, const char* description)
{
SEXP r_error = PROTECT(Rf_ScalarInteger(error));
SEXP r_description = PROTECT(Rf_mkString(description));
SEXP call = PROTECT(Rf_lang3(rcallback, r_error, r_description));
// `call` is evaluated for its side effects, so no need to store and/or
// PROTECT the result from its evaluation.
Rf_eval(call, R_GlobalEnv);
UNPROTECT(3);
return;
}
SEXP glfw_set_error_callback_(SEXP callback) {
rcallback = callback;
glfwSetErrorCallback(error_cb);
return R_NilValue;
}

Progress 4GL In-line functions / Multi-line statement

Description:
I am Writing/Editing a LinqToProgress query engine. So far simple functions within progress is simple to replicate, such as "A" >= "B" or Lookup(A, B) > 1, simple one liners that give boolean conditions. However to implement more advance function or custom functions I will need to be able to write multiline statements that can be plugged into conditions, meaning the inline function should be able to give a boolean result when you use DISP ( myFunc ) in the ABL ScratchPad (Using Eclipse) or similar programs.
Issue:
I need to convert the code between the //Start Here and //End Here to an inline boolean result.
DEF VAR i AS INT NO-UNDO.
DEF VAR LIST AS CHAR NO-UNDO INIT "one,two,three,four".
DEF VAR LIST2 AS CHAR NO-UNDO INIT "one,three,five".
DISP(
// Start Here
DO i=1 TO NUM-ENTRIES(LIST):
IF LOOKUP(ENTRY(i, LIST),LIST2) > 0 THEN RETURN TRUE.
END.
RETURN FALSE.
// End Here
)
Currently the code throws an error.
White space after colon ends statement. I tried looking for solutions on multiline statements/inline functions but so far found nothing.
Constraints:
Everything written needs to be contained within the Disp function.
I can't use previously created functions.
You should introduce a method or function that contains your code block. The ABL does not support statements and blocks as an expression.

How to prevent closure compiler from removing unused local variable?

I am facing one scenario as below,
function a() {
var $$ = this;
eval("some script");
}
using closure compiler with simple level, it will remove the $$ var in the simplified output, but this variable maybe used by the code "some script" from script developers, so is there anyway to let closure compiler keep var $$ in the output? Thanks!
Borrowing from Solution: Export the Symbols You Want to Keep I suggest you use a bracket notation to create this var. I'm assuming that your global element is window.
function a() {
window['$$'] = this;
eval("some script");
}
It might not be pretty, but this does work;
With an output of
function a() {
window.$$ = this;
eval("some script");
}
No not really. You might be able to find a workaround, but it's not guaranteed to work in future compiler versions.
You would need to rework you code not to utilize eval like that.
Use the Function constructor:
var a = new Function('var $$ = this; eval("some script");');
If you want to avoid escaping the contents of "some script", you can pass it in as parameter:
var a = new Function('script', 'var $$ = this; eval(script);');
This keeps needed locals out of the compiler's analysis.

C++ Static vector loses data after exiting function

I have a static function:
void TextManager::printDialogue(vector<Button*>* options, int optionsCount, vector<string> outputDisplayText)
{
active = true;
buttons = *options;
buttonsCount = optionsCount;
outputText = outputDisplayText;
}
The "buttons" variable is static:
static vector<Button*> buttons;
I make a call to printDialogue in an execute function:
void WorldDoor::execute()
{
vector<Button*> buttons;
buttons.push_back(new CancelButton());
buttons.push_back(new ChangeRoomButton(room));
TextManager::printDialogue(&buttons, 2, messages); //<----
std::vector<Button*>::iterator i = buttons.begin();
for ( i = buttons.begin() ; i < buttons.end(); i++ )
{
delete * i;
}
}
For whatever reason, when I debug and have a break point inside of the printDialogue function, the values in "buttons" are perfectly fine. However, after I leave printDialogue, the strings contained in my buttons go from being readable to giving me an error message saying:
I tried passing a pointer to an array instead of using
vector<Button*>
but it was only reading the first variable. Now it is not reading anything. Could anyone please help?
There is a static member variable called buttons, and also a local variable inside execute() called buttons. You should rename to avoid confusion, otherwise, the local variable will be used instead of the static member variable inside execute().
Edit: Completely misunderstood the question.
When you do this:
vector<int*> vector1;
vector<int*> vector2;
vector1.push_back(new int(5));
vector2 = vector1;
It copies the pointers, not the value of the pointers.
So when you later iterate over the first vector and delete the dynamic memory, both vectors have pointers pointing to the same memory that you deleted, so your second vector is pointing to invalid memory.
If you are using C++11, you can use a vector of unique pointers, and std::move() one vector into another.
Otherwise, you can just call 'clear()' on the vector, without deleting the memory.
Here's how the function could be written:
void TextManager::printDialogue(vector<Button*>* options, int optionsCount, vector<string> outputDisplayText)
{
active = true;
buttons = *options;
options->clear(); //<--- Instead of crawling over it and delete-ing it.
buttonsCount = optionsCount;
outputText = outputDisplayText;
}
Everything below this was my misunderstanding the question: (contains other information that might be important)
When you do:
vector<Button*> buttons;
Inside the function, you are creating a new vector called 'buttons', which gets destroyed at the end of the function call.
If you want to access the global one, don't create a new one inside the function, or name them something different.
Example:
int myVar = 100; //Declares a variable called 'myVar' at global scope.
void func()
{
int myVar = 200; //Declares a *different* variable called 'myVar' at function scope.
std::cout << myVar << std::endl; //Prints the one inside the function, not the one outside it.
}
By the way, the variable 'static' shouldn't be used at global scope, unless the variable belongs to a class.
To make a variable global, you just put it outside of any function. To make a class member shared between all instances of that class, you declare it static so that class knows to have all instances share the one variable. It's a different thing. =)
If you have your code split into multiple files, to make a global really-truly global, you have to declare it 'extern' in your header, and not extern in one source file, and have other source files #include the header that externs it. Slightly clunky, but that's how it's done. They are working on a better system for it, but it'll be several years before it becomes standardized.

Resources