How to pass a file pointer to a different function - file

If I have created a file in my main() function:
output, err := os.Create("D:\\output.txt")
And I want everything that another function in the program prints, to be put in that file using:
output.WriteString(str)
How could I pass a pointer to that file so that function could write to it?
Also, is there any other way I should use to write a string to a file, or WriteString is succicient?

Have your function take a pointer as a parameter using the * type modifier, and just pass your file object as-is since os.Create already returns a pointer:
func WriteStringToFile(f *os.File) {
n, err := f.WriteString("foobar")
}
// ..
output, err := os.Create("D:\\output.txt")
WriteStringToFile(output)
Also, please note that it is good practice not to ignore errors.
To write strings into a file can be done in a few different ways, especially if you want to avoid using the os.File object directly, and only use the io.Writer interface. For example:
fmt.Fprint(output, "foo bar")

Using an interface such as io.Writer is the way to go. Many types in Go fulfill the io.Writer just by having a Write method. os.File is one of those types.

Simply define a function that can take *File pointer as argument:
func Write(output *os.File) {
(...)
}
Write(&output) //call function.
}
Also you may want to ensure that file is closed in the end using:
defer output.Close()

Related

Issue with checking a Path and reading the file in Rust

I have an issue with trying to check if a file exists and reading it if it exists.
My code:
use std::{env, fs};
use std::fs::{File, read};
use std::path::Path;
use std::process::exit;
let arg = env::args().next().expect("Please open a file via the command line!");
let path = Path::new(
&arg
);
if !path.exists() {
error!("The specified path does not exist!");
exit(101);
}
let file = read(path).expect("Could not read file!");
let content = String::from_utf8(file).expect("The file does not contain valid characters!");
Run the program like this ./program.exe a_vali_file_path.txt
Expectation:
If you run the program with a valid file path as the first argument, the program will check if it exists. If it does, the program reads the file content and just returns.
What actually happened:
The program doesn't even really check for the file (it does not panic, even if the path is not valid) and if it tries to read it prints a bunch of bytes into the console followed by the error
error: Utf8Error { valid_up_to: 2, error_len: Some(1) } }.
This behavior occurs if the file exists or not.
env::args.next() references the executable, which doesn't contain UTF-8 bytes. If you want to point to the next argument you must use another .next() call, or better yet use a Vector to store your args.
Example of a vector being used to store args ->
fn main() {
let args: Vec<String> = env::args().collect()
...
}
To solve it your way:
fn main() {
let args = env::args()
args.next() //Points to executable (argv[0])
args.next() //Points to file (argv[1])
}
As you can see the second solution is not very elegant, but hey, to each their own.

.C() returns me an empty list

I'm a beginner in R and I'm trying to load a .dll file, named dll.dll, that's written in C, into R. It seems to work, now I want to use the functions that are stored in the .dll file and I encounter problems.
I've searched for a solution or other method in manuals, here and on google. Would be very thankful if I could get a suggestion of what to use or any idea!
My code:
setwd("C:/Users/MyUser/R")
dyn.load("dll.dll")
is.loaded("DLL_FUNK")
# For some reason True with capital letters, not in lower case
output <- .C("DLL_FUNK", in9 = as.integer(7))
#output # R Crashes before I can write this.
# R Crashes
# In outdata.txt: "in-value= 139375128"
The function should return a number, 1955. But I can't seem to get to that value. What am I doing wrong?
Update with code (Fortran runned as C), this is the code in dll.dll:
subroutine dll_funk(in9)
implicit none
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!*** Declarations: variables, functions
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
integer(4) :: in9
!integer :: in9
! Definitions of variables in the external function calls
!!dec$ attributes c,alias :'dll_funk' :: dll_funk
!dec$ attributes dllexport :: dll_funk
!dec$ attributes value :: in9
open(194,file='outdata.txt')
write(194,*) 'in-value=', in9
! in9 = 1955
close(194)
end subroutine
!end function
So now when it runs, R crashes but before it writes to my file (outdata.txt) but it't not my number, maybe some kind of address...
Another question, do you recommend me to run the code with .C and from C run the Fortran code or is it better to run it with .Fortran with only Fortran code?
It seems like .Fortran have problem handling strings, or that's what I understood from: Interface func .C and .Fortran
Why did not you pass any arguments to your C function dll_function? When you use .C(), you have to pass function arguments as a list. .C() will return modified list. So, If you pass in nothing, you get nothing.
What does your C function dll_function looks like? Note that:
dll_function must be a void C function, with no return values. If this function should return something, it must return by modifying function arguments;
all function arguments of dll_function must be pointers.
Follow-up
The dll_function is only to test if I can get access to it.
You can use is.loaded() after dyn.load() to test whether you have access to the C function:
dyn.load("dll.dll")
is.loaded("dll_function") ## TRUE
Note that, is.loaded takes C function name, while dyn.load() takes .dll name. In general you can have multiple functions in a single .dll file. You can use is.loaded() to check either of them, to test whether shared library has been loaded successfully.
So if I want it to return something, I should give it an argument (of same type?)?
Yes. The other answer here does give a toy example. You can have a look at this answer I made half a month ago. At the bottom there is a summary of variable type.
When using .C, the extra arguments passed to .C are copied and passed on as pointers to the called c-function. This function can then modify the data pointer to by the pointers. The return value of the function is ignored by .C. So, you c-function should look something like:
void dll_function(int* result) {
/* Do some complicated computation that results in 1955 */
(*result) = 1955;
}
And your call from R:
.C("dll_function", integer(1))
An example with input (this calculates the sum of an integer vector; this example assumes that there are no missing values in vector):
void dll_function2(int* result, int* vector, int* length) {
int sum = 0;
for (int i = 0; i < (*length); ++i, ++vector) {
sum += (*vector)
}
(*result) = sum;
}
Called from R:
x <- c(1000, 900, 55)
.C("dll_function2", integer(1), as.integer(x), length(x))[[1]]

calling mruby VM in C++

I am trying to convert some of the ruby interpreter code called in C to mruby format. I am stuck and would appreciate help here.
My testruby.rb file content:
#require 'MyMod'
def helloworld(var1)
puts "You said #{var1}"
return MyMod.Issue1(var1).to_s
end
Below is the snippet of my C++ file:
Issue 1:
static mrb_value Issue1(mrb_state *mrb, mrb_value mrb_self)
{
mrb_??? val1; // What should be the type for string and where to find all the types?
mrb_get_args(mrb, "s", ?);
// How to manipulate val1? Say I want to concatenate few more data.
return mrb_????(val1); // How do I return this value?
}
The above method, I am sending as a module to the mruby interpreter so that .rb file can call this.
Please let me know if below format is the correct one:
struct RClass *mod = mrb_define_module(mrb, "MyMod");
mrb_define_module_function(mrb, mod, "SumI", Issue1, MRB_ARGS_REQ(1));
Issue2:
How do I convert the below ruby interpreter code to mruby?
rb_require("./testruby"); // where testruby is my testruby.rb file
Now I want to call the helloworld method from testruby.rb file. How do I call the equivalent method for mruby (for rb_funcall)?
How do I read the return value from the helloworld method in my c++ code?
Regards,
Re val1: mrb_value is the type that can hold any mruby object
Manipulating val1 could be done using mrb_funcall. That function returns a mrb_value:
mrb_value my_str = mrb_funcall(mrb_context, your_object, "your_method", 0);
printf("my_str = %s\n", RSTRING_PTR(my_str));
Re issue 2: There's no require in mruby: mrbgems are compiled and linked statically with the target binary (they are listed in the top-level build_config.rb file).
(A gem called mruby-require exists to mimic CRuby's require, but I've never used it)

Read a C-type string from Go

I am trying to write a simple OpenGL application in Go and would like to read the OpenGL Version from the driver. I am using this function:
http://godoc.org/github.com/chsc/gogl/gl21#GetString
which is a wrapper function for
const GLubyte* glGetString( GLenum name);
This code:
fmt.Println(gl.GetString(gl.RENDERER))
fmt.Println(*gl.GetString(gl.VERSION))
outputs
0x4708ae0
50
The output is probably a C-type string, pointer to the first byte of the string. How can I convert the output from the GetString function into a normal go string?
Solution:
The package provided the right converter function, it is just not really obvious:
fmt.Println( gl.GoStringUb( gl.GetString( gl.RENDERER )))
General approach: (if the package wouldn't provide a *Ubyte to string conversion function)
pointer := unsafe.Pointer(gl.GetString(gl.RENDERER))
str := C.GoString( (*C.char)(pointer) )
fmt.Println(str)
The package you linked provides a function GoStringUb that does the trick:
render := gl.GoStringUb(gl.GetString(gl.RENDERER))
version := gl.GoStringUb(gl.GetString(gl.VERSION))

Call Go functions from C

I am trying to create a static object written in Go to interface with a C program (say, a kernel module or something).
I have found documentation on calling C functions from Go, but I haven't found much on how to go the other way. What I've found is that it's possible, but complicated.
Here is what I found:
Blog post about callbacks between C and Go
Cgo documentation
Golang mailing list post
Does anyone have experience with this? In short, I'm trying to create a PAM module written entirely in Go.
You can call the Go code from C. It is a confusing proposition, though.
The process is outlined in the blog post you linked to. But I can see how that isn't very helpful. Here is a short snippet without any unnecessary bits. It should make things a little clearer.
package foo
// extern int goCallbackHandler(int, int);
//
// static int doAdd(int a, int b) {
// return goCallbackHandler(a, b);
// }
import "C"
//export goCallbackHandler
func goCallbackHandler(a, b C.int) C.int {
return a + b
}
// This is the public function, callable from outside this package.
// It forwards the parameters to C.doAdd(), which in turn forwards
// them back to goCallbackHandler(). This one performs the addition
// and yields the result.
func MyAdd(a, b int) int {
return int( C.doAdd( C.int(a), C.int(b)) )
}
The order in which everything is called is as follows:
foo.MyAdd(a, b) ->
C.doAdd(a, b) ->
C.goCallbackHandler(a, b) ->
foo.goCallbackHandler(a, b)
The key to remember here is that a callback function must be marked with the //export comment on the Go side and as extern on the C side. This means that any callback you wish to use, must be defined inside your package.
In order to allow a user of your package to supply a custom callback function, we use the exact same approach as above, but we supply the user's custom handler (which is just a regular Go function) as a parameter that is passed onto the C side as void*. It is then received by the callbackhandler in our package and called.
Let's use a more advanced example I am currently working with. In this case, we have a C function that performs a pretty heavy task: It reads a list of files from a USB device. This can take a while, so we want our app to be notified of its progress. We can do this by passing in a function pointer that we defined in our program. It simply displays some progress info to the user whenever it gets called. Since it has a well known signature, we can assign it its own type:
type ProgressHandler func(current, total uint64, userdata interface{}) int
This handler takes some progress info (current number of files received and total number of files) along with an interface{} value which can hold anything the user needs it to hold.
Now we need to write the C and Go plumbing to allow us to use this handler. Luckily the C function I wish to call from the library allows us to pass in a userdata struct of type void*. This means it can hold whatever we want it to hold, no questions asked and we will get it back into the Go world as-is. To make all this work, we do not call the library function from Go directly, but we create a C wrapper for it which we will name goGetFiles(). It is this wrapper that actually supplies our Go callback to the C library, along with a userdata object.
package foo
// #include <somelib.h>
// extern int goProgressCB(uint64_t current, uint64_t total, void* userdata);
//
// static int goGetFiles(some_t* handle, void* userdata) {
// return somelib_get_files(handle, goProgressCB, userdata);
// }
import "C"
import "unsafe"
Note that the goGetFiles() function does not take any function pointers for callbacks as parameters. Instead, the callback that our user has supplied is packed in a custom struct that holds both that handler and the user's own userdata value. We pass this into goGetFiles() as the userdata parameter.
// This defines the signature of our user's progress handler,
type ProgressHandler func(current, total uint64, userdata interface{}) int
// This is an internal type which will pack the users callback function and userdata.
// It is an instance of this type that we will actually be sending to the C code.
type progressRequest struct {
f ProgressHandler // The user's function pointer
d interface{} // The user's userdata.
}
//export goProgressCB
func goProgressCB(current, total C.uint64_t, userdata unsafe.Pointer) C.int {
// This is the function called from the C world by our expensive
// C.somelib_get_files() function. The userdata value contains an instance
// of *progressRequest, We unpack it and use it's values to call the
// actual function that our user supplied.
req := (*progressRequest)(userdata)
// Call req.f with our parameters and the user's own userdata value.
return C.int( req.f( uint64(current), uint64(total), req.d ) )
}
// This is our public function, which is called by the user and
// takes a handle to something our C lib needs, a function pointer
// and optionally some user defined data structure. Whatever it may be.
func GetFiles(h *Handle, pf ProgressFunc, userdata interface{}) int {
// Instead of calling the external C library directly, we call our C wrapper.
// We pass it the handle and an instance of progressRequest.
req := unsafe.Pointer(&progressequest{ pf, userdata })
return int(C.goGetFiles( (*C.some_t)(h), req ))
}
That's it for our C bindings. The user's code is now very straight forward:
package main
import (
"foo"
"fmt"
)
func main() {
handle := SomeInitStuff()
// We call GetFiles. Pass it our progress handler and some
// arbitrary userdata (could just as well be nil).
ret := foo.GetFiles( handle, myProgress, "Callbacks rock!" )
....
}
// This is our progress handler. Do something useful like display.
// progress percentage.
func myProgress(current, total uint64, userdata interface{}) int {
fc := float64(current)
ft := float64(total) * 0.01
// print how far along we are.
// eg: 500 / 1000 (50.00%)
// For good measure, prefix it with our userdata value, which
// we supplied as "Callbacks rock!".
fmt.Printf("%s: %d / %d (%3.2f%%)\n", userdata.(string), current, total, fc / ft)
return 0
}
This all looks a lot more complicated than it is. The call order has not changed as opposed to our previous example, but we get two extra calls at the end of the chain:
The order is as follows:
foo.GetFiles(....) ->
C.goGetFiles(...) ->
C.somelib_get_files(..) ->
C.goProgressCB(...) ->
foo.goProgressCB(...) ->
main.myProgress(...)
It is not a confusing proposition if you use gccgo. This works here:
foo.go
package main
func Add(a, b int) int {
return a + b
}
bar.c
#include <stdio.h>
extern int go_add(int, int) __asm__ ("example.main.Add");
int main() {
int x = go_add(2, 3);
printf("Result: %d\n", x);
}
Makefile
all: main
main: foo.o bar.c
gcc foo.o bar.c -o main
foo.o: foo.go
gccgo -c foo.go -o foo.o -fgo-prefix=example
clean:
rm -f main *.o
The answer has changed with the release of Go 1.5
This SO question that I asked some time ago addresses the issue again in light of the 1.5 added capabilities
Using Go code in an existing C project
As far as I am concerned it isn't possible:
Note: you can't define any C functions in preamble if you're using
exports.
source: https://github.com/golang/go/wiki/cgo

Resources