In RcppArmadillo, I need to know how I can convert arma::mat to c-style array double * for use in other functions.
When I run the following functions, the computer crashes:
R part:
nn3 <- function(x){
results=.Call("KNNCV", PACKAGE = "KODAMA", x)
results
}
C++ part:
double KNNCV(arma::mat x) {
double *cvpred = x.memptr();
return cvpred[1];
}
and at the end, I try:
nn3(as.matrix(iris[,-5]))
Can you help me to find the errors, please?
First, there is no such such thing as vector stored in a double*. You can cast to a C-style pointer to double; but without length information that does not buy you much.
By convention, most similar C++ classes give you a .begin() iterator to the beginning of the memory block (which Armadillo happens to guarantee to be contiguous, just like std::vector) so you can try that.
Other than that the (very fine indeed) Armadillo documentation tells you about memptr() which is probably what you want here. Straight copy from the example there:
mat A = randu<mat>(5,5);
const mat B = randu<mat>(5,5);
double* A_mem = A.memptr();
const double* B_mem = B.memptr();
Related
I have an Rcpp script where I do the following:
double m = runif(1); // generate a random number uniformly between 0 and 1.
I then pass m to sample() as follows:
IntegerVector ind = RcppArmadillo::sample<IntegerVector>(perms, ceil(num_specs * m), false); // int perms, num_specs.
The above line results in an error:
error: no viable conversion from 'NumericVector' (aka 'Vector<14>') to 'double'
Unless my thinking (or declarations) is flawed, runif(1) is a scalar (double) not a vector (NumericVector).
The above works fine when I declare:
double m = 0;
Could someone point out how to get around the issue with runif()?
Have a look at the RcppArmadilloExtensions/ directory in the RcppArmadillo header directory -- there is an entire sample() example set up for RcppArmadillo.
And there are
a first Rcpp Gallery post
a second Rcpp Gallery post
with an examples for sampling using it.
Otherwise your problem may be one of confusing the scalar R::runif() (using the C API of R) with the vectorised Rcpp::runif() returning a vector. If you are more explicit about which one you use (i.e. explicit namespacing with ::) your code may still work.
I've asked a question here, and that led me to an another question.
In R, there's no fundamental distinction between a string and a
character. A "string" is just a character variable that contains one
or more characters.
and
There is a distinction between a scalar character variable, and a
vector. A character vector is a set of strings stored as a single
object.
So I wonder how to allocate a string with c api of R? For example, what do I get from:
result = Rf_allocVector(STRSXP, dst_size);
is it(the result) a scalar character variable or a vector? or could I use other API for allocating string?
Thanks.
We have that as a motivating example in our introductory vignette in the Rcpp package (and this is also published as a paper JSS in 2011):
In the C API you must do allocate a vector of STRSXP:
SEXP ab;
PROTECT(ab = allocVector(STRSXP, 2));
SET_STRING_ELT( ab, 0, mkChar("foo") );
SET_STRING_ELT( ab, 1, mkChar("bar") );
UNPROTECT(1);
which imposes on the programmer knowledge of PROTECT, UNPROTECT,
SEXP, allocVector, SET_STRING_ELT, and mkChar.
Whereas with Rcpp and
using the Rcpp::CharacterVector class, we can express the same code more concisely:
Rcpp::CharacterVector ab(2);
ab[0] = "foo";
ab[1] = "bar";
Ok, so I am a little lost with Processing Programming Language again, so wondering if anyone can help my brain become unblocked?
This is the question - "Write a program which compares two numbers, if one of the numbers is larger than the other then the two numbers are added together and the result is printed in the console window."
So I have got this, but im getting errors on just the 'int' value code which is making me think ive completely misunderstood this?.. possibly misunderstood how the language works :/
Here is my code;
void setup() {
int a = 30
int b = 20
if (a > b) {printIn("a+b");}
}
Generally it helps if you post what errors you're getting. However, in this case you have a very basic syntax problem: you need to terminate your statements with semicolons - including the assignments. Eg: int a = 30;
Oh, and it's println (with a lowercase L) not printIn. And, as noted by logoff, you're doing the sum inside a quoted string, which will just print as a literal.
If I understad it correctly you have to declare the variables outside the setup() method. Intialization can be done inside the method.
The l in println(); should be lowercase.
There is no need for the quotes around the variables.
This works:
void setup() { int a = 30; int b = 20; if(a > b) {println(a + b); }}
I'm having an absolute hell of a time trying to figure out how to get a plain, mutable C string (a char*) from a D string (a immutable(char)[]) to that I can pass the character data to legacy C code. toStringz doesn't work, as I get an error saying that I "cannot implicitly convert expression (toStringz(this.fileName())) of type immutable(char)* to char*". Do I need to recreate a new, mutable array of char and copy the characters over?
If you can change the header of the D interface of that legacy C code, and you are sure that legacy C code will not modify the string, you could make it accept a const(char)*, e.g.
char* strncpy(char* dest, const(char)* src, size_t count);
// ^^^^^^^^^^^^
Yeah, it's not pretty, because the result is immutable.
This is why I always return a mutable copy of new arrays in my code. There's no point in making them immutable.
Solutions:
You could just do
char[] buffer = (myString ~ '\0').dup; //Concatenate a null terminator, then dup
then use buffer.ptr as the pointer.
However:
This wastes a string. A better approach might be:
char[] buffer = myString.dup;
buffer ~= '\0'; //Hopefully this doesn't reallocate
and using buffer.ptr afterwards.
Another solution is to use a method like this one:
char* toStringz(in char[] s)
{
string result;
if (s.length > 0 && s[$ - 1] == '\0') //Is it null-terminated?
{ result = s.dup; }
else { result = new char[s.length + 1]; result[0 .. s.length][] = s[]; }
return result.ptr;
}
This one is the most efficient but also the longest.
(Edit: Whoops, I had a typo in the if; fixed it.)
If you want to pass a mutable char* to a C function, you're going to need to allocate a mutable char[]. string isn't going to work, because it's immutable(char)[]. You can't alter immutable variables, so there is no way to pass a string to a function (C or otherwise) which needs to alter its elements.
So, if you have a string, and you need to pass it to a function which takes a char[], then you can use to!(char[]) or dup and get a mutable copy of it. In addition, if you want to pass it to a C function, you're going to need to append a '\0' to it so that it's zero-terminated. The easiest way to do that is just to do ~= '\0' on the char[], but the more efficient way would probably be to do something like this:
auto cstring = new char[](str.length + 1);
cstring[0 .. str.length] = str[];
cstring[$ - 1] = '\0';
In either case, you then pass cstring.ptr to the C function that you're calling.
If you know that the C function that you're calling isn't going to alter the string, then you can either do as KennyTM suggests and alter the C function's signature in D to take a const(char)*, or you can cast the string. e.g.
auto cstring = toStringz(str);
cfunc(cast(char*)cstring.ptr);
Altering the C function's signature would be more correct and less error-prone though.
It sounds like we may be altering std.conv.to to be smart enough to turn strings into zero-terminated strings when cast to char*, const(char)*, etc. So, once that's done, getting a zero-terminated mutable string should be easier, but for the moment, you pretty much just need to copy the string and append a '\0' to it so that it's zero-terminated. But regardless, you're never going to be able to pass a string to a C function which needs to modify it, because a string can't be mutated.
Without any context on which function you're calling it's hard to say what is the right solution.
Typically, if the C function wants to modify or write to the string it probably expects you to provide a buffer and a length. Usually what I do is:
Allocate a buffer:
auto buffer = new char[](256); // your own length instead of 256 here
And call the C function:
CWriteString(buffer.ptr, buffer.length);
You can try the following :
char a[]="abc";
char *p=a;
Now you can pass pointer 'p' to the array in any function.
Hope it works.
I was wondering. Are there languages that use only pass-by-reference as their eval strategy?
I don't know what an "eval strategy" is, but Perl subroutine calls are pass-by-reference only.
sub change {
$_[0] = 10;
}
$x = 5;
change($x);
print $x; # prints "10"
change(0); # raises "Modification of a read-only value attempted" error
VB (pre .net), VBA & VBS default to ByRef although it can be overriden when calling/defining the sub or function.
FORTRAN does; well, preceding such concepts as pass-by-reference, one should probably say that it uses pass-by-address; a FORTRAN function like:
INTEGER FUNCTION MULTIPLY_TWO_INTS(A, B)
INTEGER A, B
MULTIPLY_BY_TWO_INTS = A * B
RETURN
will have a C-style prototype of:
extern int MULTIPLY_TWO_INTS(int *A, int *B);
and you could call it via something like:
int result, a = 1, b = 100;
result = MULTIPLY_TWO_INTS(&a, &b);
Another example are languages that do not know function arguments as such but use stacks. An example would be Forth and its derivatives, where a function can change the variable space (stack) in whichever way it wants, modifying existing elements as well as adding/removing elements. "prototype comments" in Forth usually look something like
(argument list -- return value list)
and that means the function takes/processes a certain, not necessarily constant, number of arguments and returns, again, not necessarily a constant, number of elements. I.e. you can have a function that takes a number N as argument and returns N elements - preallocating an array, if you so like.
How about Brainfuck?