I need to return few values from rust function. Tried to declare function which returns an array
$ffi = FFI::cdef('float get_arr()[2];', './target/release/libphp_rust.dylib');
$array = $ffi->get_arr();
But got an error:
PHP Fatal error: Uncaught FFI\ParserException: function returning array is not allowed at line 1 in /array.php:3
It seems PHP FFI can't work with arrays directly. So I found another solution.
I created C-array from PHP, then passed pointer to it to Rust code and then populated it with Rust function:
$ffi = FFI::cdef('bool get_arr(float (*res)[2]);', './target/release/libphp_rust.dylib');
$array = $ffi->new('float[2]');
$result = $ffi->get_arr(FFI::addr($array));
if ($result) {
var_dump($array);
} else {
//... something went wrong
}
#[no_mangle]
pub extern fn get_arr(array_pointer: *mut [f32;2]) -> bool {
let res = unsafe {
assert!(!array_pointer.is_null());
&mut *array_pointer
};
res[0] = 0.1;
res[1] = 0.2;
return true;
}
This solutions seems to work correct but i have some doubts about it:
Is passing pointers to FFI safe enough and what problems may I face with this in future?
Are Rust arrays fully C-compatible so that I'm able to assign value to it directly by index?
I there better way to achieve what I need? Or maybe are there some good practices about passing complex data structures with FFI?
Thanks
The rules surrounding this are still up in the air, so your example is questionably safe. This should be ok, but requires nightly features:
#![feature(maybe_uninit_extra)]
#![feature(ptr_as_uninit)]
// Make sure you use `extern "C"`. `extern` alone means `extern "Rust"`.
#[no_mangle]
pub extern "C" fn get_arr(array_pointer: *mut [f32; 2]) -> bool {
let fat: *mut [f32] = array_pointer;
let res = unsafe { fat.as_uninit_slice_mut().unwrap() };
res[0].write(0.1);
res[1].write(0.2);
true
}
On the stable channel it's just less elegant:
// Make sure you use `extern "C"`. `extern` alone means `extern "Rust"`.
#[no_mangle]
pub extern "C" fn get_arr(array_pointer: *mut [f32; 2]) -> bool {
assert!(!array_pointer.is_null());
unsafe {
let res = array_pointer as *mut f32;
res.add(0).write(0.1);
res.add(1).write(0.2);
}
true
}
In a previous Using R, how to reference variable variables (or variables variable) a la PHP[post]
I asked a question about something in R analagous to PHP $$ function:
Using R stats, I want to access a variable variable scenario similar to PHP double-dollar-sign technique: http://php.net/manual/en/language.variables.variable.php
Specifically, I am looking for a function in R that is equivalent to $$ in PHP.
The get( response works for strings (characters).
lapply is a way to loop over lists
Or I can loop over and get the values ...
for(name in names(vars))
{
val = vars[[name]];
I still haven't had the $$ function in R answered, although the lapply solved what I needed in the moment.
`$$` <- function
that allows any variable type to be evaluated. That is still the question.
UPDATES
> mlist = list('four'="score", 'seven'="years");
> str = 'mlist$four'
> mlist
$four
[1] "score"
$seven
[1] "years"
> str
[1] "mlist$four"
> get(str)
Error in get(str) : object 'mlist$four' not found
> mlist$four
[1] "score"
Or how about attributes for an object such as mobj#index
UPDATES #2
So let's put specific context on the need. I was hacking the texreg package to build a custom latex output of 24 models of regression for a research paper. I am using plm fixed effects, and the default output of texreg uses dcolumns to center, which I don't like (I prefer r#{}l, so I wanted to write my own template. The purpose for me, to code this, is for me to write extensible code that I can use again and again. I can rebuild my 24 tables across 4 pages in seconds, so if the data change, or if I want to tweak the function, I immediately have a nice answer. The power of abstraction.
As I hacked this, I wanted to get more than the number of observations, but also the number of groups, which can be any user defined index. In my case it is "country" (wait for it, hence, the need for variable variables).
If I do a lookup of the structure, what I want is right there: model$model#index$country which would be nice to simply call as $$('model$model#index$country'); where I can easily build the string using paste. Nope, this is my workaround.
getIndexCount = function(model,key="country")
{
myA = attr(summary(model)$model,"index");
for(i in 1:length(colnames(myA)))
{
if(colnames(myA)[i] == key) {idx = i; break;}
}
if(!is.na(idx))
{
length(unique(myA[,idx]));
} else {
FALSE;
}
}
UPDATES #3
Using R, on the command line, I can type in a string and it gets evaluated. Why can't that internal function be directly accessed, and the element captured that then gets printed to the screen?
There is no equivalent function in R. get() works for all types, not just strings.
Here is what I came up with, after chatting with the R-bug group, and getting some ideas from them. KUDOS!
`$$` <- function(str)
{
E = unlist( strsplit(as.character(str),"[#]") );
k = length(E);
if(k==1)
{
eval(parse(text=str));
} else {
# k = 2
nstr = paste("attributes(",E[1],")",sep="");
nstr = paste(nstr,'$',E[2],sep="");
if(k>2) {
for(i in 3:k)
{
nstr = paste("attributes(",nstr,")",sep="");
nstr = paste(nstr,'$',E[i],sep="");
}
}
`$$`(nstr);
}
}
Below are some example use cases, where I can directly access what the str(obj) is providing... Extending the utility of the '$' operator by also allowing '#' for attributes.
model = list("four" = "score", "seven"="years");
str = 'model$four';
result = `$$`(str);
print(result);
matrix = matrix(rnorm(1000), ncol=25);
str='matrix[1:5,8:10]';
result = `$$`(str);
print(result);
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14);
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69);
group <- gl(2, 10, 20, labels = c("Ctl","Trt"));
weight <- c(ctl, trt);
lm.D9 <- lm(weight ~ group);
lm.D90 <- lm(weight ~ group - 1); # omitting intercept
myA = anova(lm.D9); myA; str(myA);
str = 'myA#heading';
result = `$$`(str);
print(result);
myS = summary(lm.D90); myS; str(myS);
str = 'myS$terms#factors';
result = `$$`(str);
print(result);
str = 'myS$terms#factors#dimnames';
result = `$$`(str);
print(result);
str = 'myS$terms#dataClasses#names';
result = `$$`(str);
print(result);
After realizing the back-tick can be a bit tedious, I chose to update the function, calling it access
access <- function(str)
{
E = unlist( strsplit(as.character(str),"[#]") );
k = length(E);
if(k==1)
{
eval(parse(text=str));
} else {
# k = 2
nstr = paste("attributes(",E[1],")",sep="");
nstr = paste(nstr,'$',E[2],sep="");
if(k>2) {
for(i in 3:k)
{
nstr = paste("attributes(",nstr,")",sep="");
nstr = paste(nstr,'$',E[i],sep="");
}
}
access(nstr);
}
}
I have a bit of PHP code that works fine on my production server but not on my test server. Here is the code:
function callProcedure0(&$connection, $procname, $dofunction)
{
mysqli_multi_query($connection, "CALL " . $procname . "();");
$first_result = 1;
do
{
$query_result = mysqli_store_result($connection);
if ($first_result)
{
$dofunction($query_result);
$first_result = 0;
}
if ($query_result)
{
mysqli_free_result($query_result);
}
$query_result = NULL;
} while(mysqli_next_result($connection));
}
...
function doGenres($in_result)
{
global $genre_array, $game_array, $genre_order_array;
$genre_count = 1;
// foreach is necessary when retrieving values since gaps may appear in the primary key
while ($genre_row = mysqli_fetch_row($in_result)) // line 81 is here!
{
$genre_array[] = $genre_row[0];
$genre_order_array[$genre_row[1] - 1] = $genre_count;
$game_array[] = [[],[]];
$genre_count += 1;
}
}
...
callProcedure0($con, "get_genres_front", doGenres); // line 138 is here!
The "get_genres_front" bit refers to a stored procedure on my database. Here are the errors:
Notice: Use of undefined constant doGenres - assumed 'doGenres' in /opt/lampp/htdocs/keyboard/keyboard.php on line 138
Again, there are no problems on the production server which is using Apache 2.2.23, MySQL 5.1.73-cll, PHP 5.4.26. The test server where things are broken is running Apache 2.4.10, MySQL 5.6.21, PHP 5.5.19.
Did something change in recent software versions? Thanks.
[edit]
This is not a duplicate question. I'm worried about the first error. I already know what to do about the second error which I have deleted.
The code you have posted is wrong, you must pass function name as string and then use call_user_func to invoke this function.
In your callProcedure0 function change
$dofunction($query_result);
to
call_user_func($dofunction, $query_result);
And then call it with the function name as string like this
callProcedure0($con, "get_genres_front", "doGenres");
The above code could work also with invoking the function with
$dofunction($query_result);
on some php versions, but the line where you pass the function name it should be string, otherwise PHP assumes it is a constant.
Currently i am learning php. Here I have a confusion this is my php code
class OBJECT_ENUM
{
const USER = 10;
const POST = 30;
const SECURE_REQUEST = 40;
}
class OPERATION_ENUM
{
const INSERT_USER = OBJECT_ENUM::USER + 1; // <- here it gives an error
const SEND_MAIL = OBJECT_ENUM::USER + 2;
const LIKE_POST = OBJECT_ENUM::POST + 1;
const INSERT_POST = OBJECT_ENUM::POST + 2;
const ENCRYPT = OBJECT_ENUM::SECURE_REQUEST + 1;
}
error message:
Parse error: syntax error, unexpected '+', expecting ',' or ';' in /var/www/workspace/6thAssignment/include/tempCall.php on line 15
I just don't understand why this error occurs.?? cany anybody explain me.??
Thank you in advance
ORIGINAL ANSWER:
As you can see in http://www.php.net/manual/en/language.oop5.constants.php:
The value must be a constant expression, not (for example) a
variable, a property, a result of a mathematical operation, or a
function call.
UPDATED:
From PHP version 5.6 now it is possible to use expressions in constants.
I think you can not do mathematical operation to be assigned to a const variable. Try changing
const INSERT_USER = OBJECT_ENUM::USER + 1;
to
$INSERT_USER = OBJECT_ENUM::USER + 1;
I believe expressions (like $a + 1) are not allowed in constants definitions, so there is why you are getting that error.
At the moment this is not allowed by PHP. There was an RFC (Request for comments) to get this added to the language:
https://wiki.php.net/rfc/const_scalar_expressions
however this was withdrawn as the author of the RFC has left the internals development team. So I suspect this may not happen any time soon but that's not to say that this won't come back in some form or another at a later date.
I'm writing a PHP extension that takes a reference to a value and alters it. Example PHP:
$someVal = "input value";
TestPassRef($someVal);
// value now changed
What's the right approach?
Edit 2011-09-13:
The correct way to do this is to use the ZEND_BEGIN_ARG_INFO() family of macros - see Extending and Embedding PHP chapter 6 (Sara Golemon, Developer's Library).
This example function takes one string argument by value (due to the ZEND_ARG_PASS_INFO(0) call) and all others after that by reference (due to the second argument to ZEND_BEGIN_ARG_INFO being 1).
const int pass_rest_by_reference = 1;
const int pass_arg_by_reference = 0;
ZEND_BEGIN_ARG_INFO(AllButFirstArgByReference, pass_rest_by_reference)
ZEND_ARG_PASS_INFO(pass_arg_by_reference)
ZEND_END_ARG_INFO()
zend_function_entry my_functions[] = {
PHP_FE(TestPassRef, AllButFirstArgByReference)
};
PHP_FUNCTION(TestPassRef)
{
char *someString = NULL;
int lengthString = 0;
zval *pZVal = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &someString, &lengthString, &pZVal) == FAILURE)
{
return;
}
convert_to_null(pZVal); // Destroys the value that was passed in
ZVAL_STRING(pZVal, "some string that will replace the input", 1);
}
Before adding the convert_to_null it would leak memory on every call (I've not whether this is necessary after adding ZENG_ARG_INFO() calls).