Say that you pass an environment R object to an internal C routine through the .Call interface. Said enviromnent has (by design) a someObject object which I want to extract and manipulate from the C side. How to do it?
To simplify my question, I just want to write a C function that returns someObject. Like this:
en <- new.env()
en$someObject <- someValue
.Call("extractObject",en)
#the above should return en$someObject
Guess the C code should then look something like
SEXP extractObject(SEXP env) {
return SOMEMACROORFUNCTION(env, "someObject");
}
Unfortunately, I was not able to find the real SOMEMACROORFUNCTION.
After a little bit of googling and searching, I've found the solution:
findVar(install("someObject"),env)
in the C code is basically the equivalent of get("someObject",env) in R.
Related
I'm writing a C user defined extension function for Postgres and would like to get the value of parameter that I set in SQL level in my C code.
For example, in SQL, I have something like:
CREATE FUNCTION my_test_function(text) RETURNS text AS 'path_to_so', 'my_function' LANGUAGE C STRICT SET some_boolean TO true;
The question is how can I get the value of some_boolean variable in my C code?
Datum my_test_function(PG_FUNCTION_ARGS) {
// try to get some_boolean here
}
some_boolean must be an existing GUC (configuration parameter), else the function definition will produce
ERROR: unrecognized configuration parameter "some_boolean"
If it is a GUC, it is either a core PostgreSQL GUG, or it was registered somewhere with DefineCustomBoolVariable (from utils/guc.h).
Each GUC belongs to a C variable, commonly a global one.
Use that variable in your code!
I know the subject has already been treated, but I've failed to find anything that works for me, so I guess my problem is slightly different from the others.
What I do, basically, is that I use a C function wrapped into a python code using ctypes.
My goal is to compute some quantities in the C function, store them into a single structure, and return the structure in Python where I could read all the different data in the structure.
So :
To define my structure in python, I use :
class BITE(ctypes.Structure):
_fields_ = [
("lum", ctypes.c_int),
("suce", ctypes.c_int)
]
I compile like that :
sub.call(["gcc","-shared","-Wl,-install_name,ex.so","-o","ex.so","-fPIC","ex.c"])
lum = ctypes.CDLL('ex.so')
lum = lum.lum
I declare the arguments and result types like this :
lum.restype = ctypes.POINTER(BITE)
lum.argtypes = [ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float]
Then, I call the C function "lum" in the python code
out = lum(all the different variables needed)
The problem begins here. I have my structure, but impossible to read the data stored in each fields.
A partial solution I found is to do :
out = out[0]
But then, when doing
print(out.suce)
I have a segmentation fault 11. DOn't know why. I tried to understand how to used create_string_buffer, but I didn't really understand how it works and what it supposed to do. Moreover, I tried to using as a black box, and still, nothing works.
I also tried some other solutions mentionned in other threads such as using out.contents or something like that, but it has no .contents attributes. Nor out.suce.value, which is also something I saw somewhere during my desperate research.
Of course, I checked in the C code that the structure exists and that each field of the structure exists, and has the right data in it.
Thanks.
Suppose you have a C-structure like this :
typedef struct _servParams
{
unsigned short m_uServPort;
char m_pInetAddr[MAX_LENGTH_OF_IP_ADDRESS];
} ServerParams_t;
To use it within ctypes you should create a wrapper like this :
class ServerParams_t(Structure):
_fields_ = [ ("m_uServPort", c_ushort),
("m_pInetAddr", (c_char * 16)) ]
Later on inside your python you can use the following snippet :
servParams = ServerParams_t()
servParams.m_uServPort = c_ushort(int(port))
servParams.m_pInetAddr = ip.encode()
If you need to pass it by value, simply pass servParams variable to you api. If you need to pass a pointer use byref(servParams).
Let's say I have a method like this:
foo (A a, B b)
I want to set expectation so that anyObject is expected except some, like the imaginary code below:
expect(mockedObject).foo(anyObject(A.class), anyObject(B.class)).andReturn(something).anyTimes();
expect(mockedObject).foo(new A("1"), new B("1")).andReturn(something).times(0);
expect(mockedObject).foo(new A("2"), new B("2")).andReturn(something).times(0);
expect(mockedObject).foo(new A("3"), new B("3")).andReturn(something).times(0);
However there is no times(0) in EasyMock. I can create a chain of EasyMock.or() and EasyMock.not() but it's going to be dirty when there are a lot of unexpected objects.
On Mockito I can easily specify
verify(mockedObject, never()).foo(new A("1"), new B("1"));
What's the easiest way on EasyMock to do the same thing as above?
It is something missing indeed.
Right now, the easier is to capture() all your parameters and then check that no invalid permutation was used.
I have a SWIG generated R wrapper which contains the following setClass operations:
setClass('_p_f_p_struct_parameters_p_struct_chromosome_p_struct_dataSet__double',
prototype = list(parameterTypes = c('_p_parameters', '_p_chromosome', '_p_dataSet'),
returnType = '_p_f_p_struct_parameters_p_struct_chromosome_p_struct_dataSet__double'),
contains = 'CRoutinePointer')
setClass('_p_f_p_struct_parameters_p_p_struct_chromosome_p_p_struct_chromosome_int_int__void',
prototype = list(parameterTypes = c('_p_parameters', '_p_p_chromosome', '_p_p_chromosome', '_int', '_int'),
returnType = '_p_f_p_struct_parameters_p_p_struct_chromosome_p_p_struct_chromosome_int_int__void'),
contains = 'CRoutinePointer')
These operation do not appear to be behaving as expected. When I call a function with the output being the creation of a _p_parameters object (defined above), I get the following error:
Error in getClass(Class, where = topenv(parent.frame())) :
“_p_parameters” is not a defined class
The setClass therefore seems to be not doing it's thing.
I tried to manually set the _p_parameters class via:
p_parameters<-setClass(Class="_p_parameters", representation = representation(ref = "externalptr"))
But this does not seem to work as when I try and modify other parameters (or even print parameters via an inbuilt function) the terminal crashes and hangs.
For reference, the final lines in initialiseParameters (the function which initially own _p_parameters) are calling the native C function via .Call then assigning the external pointer to a new object of class _p_paramters as follows:
;ans = .Call('R_swig_initialiseParameters', numInputs, numNodes, numOutputs, arity, as.logical(.copy), PACKAGE='cgp');
ans <- new("_p_parameters", ref=ans) ;
I've read various R doc on new(), setClass, S3/S4 classes but nothing seems to clarify what I'm meant to be doing here.
Any suggestions on where to start or tutorials that would give a good heads up would be most welcome.
Please keep in mind the C code is not mine (but is freely available under GNU), I am not a C programmer and am only weakly-moderately proficient in R. So please be gentle :)
Cheers.
PS: If I call the function in R terminal via .Call it works as expected (so it doesn't seem to e a C function error)
I thought I should post the solution I have to this. The least I could do for a 'tumbleweed' medal haha.
The only solution I could find to this is to comment out the following line:
ans <- new("_p_parameters", ref=ans) ;
in all function that try to create an R object.
The resulting memory pointer is then assigned to an R object at function call.
It's dirty, but I couldn't work out how to create an object from a memory pointer (at least from within the functions themselves).
It seems to work so I guess it will do.
So, I'm working on parsing a POST using GO. What I want is the body of the post, so I try the following (r is of type *http.Request in this context):
var body io.Reader
var d []byte
body = r.Body.Reader
body.Read( d)
However, this results in a compilation error:
Compile error: <file>:44:
r.Body.Reader undefined (type io.ReadCloser has no field or method Reader)
Odd. I could have sworn that it was defined in the docs... Ah! here it is.
Now, I'm fairly new to Go, but this smells a little odd -- what have I screwed up?
From your link, the doc for a ReadCloser is:
type ReadCloser interface {
Reader
Closer
}
What this is telling you, is that a ReadCloser interface is composed of a Reader and a Closer functionality. It IS both. That means the ReadCloser takes on those interface definitions. They are not actually members, the way you are accessing them.
A Reader is:
type Reader interface {
Read(p []byte) (n int, err error)
}
So that means you should be accessing Read like this:
body = r.Body
body.Read(d)
The way interfaces are defined in Go documents, it looked like it was a "has-a" relationship. It's actually an "is-a" relationship, so the following code does what I want:
var d []byte
r.Body.Read(d)