我很好奇Go是否可行.我有一个有多种方法的类型.有可能有一个函数,它接受一个方法,并可以为该类型调用它?
这是我想要的一个小例子:
package main
import (
"fmt"
)
type Foo int
func (f Foo) A() {
fmt.Println("A")
}
func (f Foo) B() {
fmt.Println("B")
}
func (f Foo) C() {
fmt.Println("C")
}
func main() {
var f Foo
bar := func(foo func()) {
f.foo()
}
bar(A)
bar(B)
bar(C)
}
Run Code Online (Sandbox Code Playgroud)
Go think类型Foo有一个名为的方法foo(),而不是用传入的方法名称替换它.
我有一个byte.Buffer,我使用binary.Write()函数打包数据.然后我需要将此字节数组发送到C函数.使用Go 1.6我没有成功解决这个问题.
buf := new(bytes.Buffer) //create my buffer
....
binary.Write(buf, binary.LittleEndian, data) //write my data to buffer here
addr := (*C.uchar)(unsafe.Pointer(&buf.Bytes()[0])) //convert buffers byte array to a C array
rc := C.the_function(addr, C.int(buf.Len())) //Fails here
Run Code Online (Sandbox Code Playgroud)
它在调用C函数的行上失败了:
panic: runtime error: cgo argument has Go pointer to Go pointer
Run Code Online (Sandbox Code Playgroud)
C函数:
int the_function(const void *data, int nbytes);
Run Code Online (Sandbox Code Playgroud)
我能够得到以下工作,但是将字节数组转换为字符串感觉不对.有一个更好的方法吗?这种方法是否会对数据产生副作用?
addr := unsafe.Pointer(C.CString(string(buf.Bytes()[0]))
Run Code Online (Sandbox Code Playgroud)
再次,这需要在Go 1.6下工作,它引入了更严格的cgo指针规则.
谢谢.
我是Go的新手,并试图学习如何从Go调用C语言.我写了这个程序来打开一个命名的信号量,获取值并将其打印到屏幕上.当我运行它时,go build semvalue.go我收到错误:
./semvalue.go:16:14: unexpected type: ...
这是什么意思?我究竟做错了什么?
package main
import "fmt"
// #cgo LDFLAGS: -pthread
// #include <stdlib.h>
// #include <fcntl.h>
// #include <sys/stat.h>
// #include <semaphore.h>
import "C"
func main() {
name := C.CString("/fram")
defer C.free(name)
fram_sem := C.sem_open(name, C.O_CREAT, C.mode_t(0644), C.uint(1))
var val int
ret := C.sem_getvalue(fram_sem, val)
fmt.Println(val)
C.sem_close(fram_sem)
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
我能够让 Zig 创建一个 C 库,但是当我尝试从 C 程序中使用所述库时,它无法找到包含函数的定义。
我的库定义:
const std = @import("std");
export fn removeAll(name: [*]const u8, len: u32) u32 {
const n: []const u8 = name[0..len];
std.fs.cwd().deleteTree(n) catch |err| {
return 1;
};
return 0;
}
test "basic remove functionality" {
}
Run Code Online (Sandbox Code Playgroud)
build.zig
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const lib = b.addStaticLibrary("removeall", "src/main.zig");
lib.setBuildMode(mode);
switch (mode) {
.Debug, .ReleaseSafe => lib.bundle_compiler_rt = true,
.ReleaseFast, .ReleaseSmall => lib.disable_stack_probing = true,
} …Run Code Online (Sandbox Code Playgroud) 如果没有反射,可以将多种类型添加到类型[] interface {}的列表中.像这样:
package main
import "fmt"
func main() {
var foo []interface{}
foo = append(foo, "Test")
foo = append(foo, "Foo")
foo = append(foo, 10)
fmt.Printf("%v\n", foo)
}
Run Code Online (Sandbox Code Playgroud)
这可能与反思有关吗?我尝试以下但我得到一个恐慌的说法:" 恐慌:reflect.Set:类型字符串的值不能分配给类型[] interface {} "
package main
import (
"fmt"
"reflect"
)
func rf(inf interface{}) {
val := reflect.Indirect(reflect.ValueOf(inf))
field := val.FieldByName("Foo")
rslice := reflect.MakeSlice(reflect.SliceOf(field.Type()), 0, 5)
v := reflect.Indirect(reflect.ValueOf("Test"))
rslice = reflect.Append(rslice, v)
}
func main() {
var s struct {
Foo []interface{}
}
rf(&s)
fmt.Printf("%+v\n", s)
}
Run Code Online (Sandbox Code Playgroud) 我已经编写了一个关于linux中信号量函数的包装器.这在过去的Go 1.3和Go 1.4中对我有用,但我需要使用这个包装器重建我的应用程序,它不再使用Go 1.6.2或Go 1.7rc5构建.
我写了一个简单的测试应用程序,产生相同的错误:
package main
import (
"fmt"
"os"
"linux/semaphore"
)
func main() {
var sema semaphore.Semaphore
if err := sema.Open("/test", 0644, 1); err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
if err := sema.TryWait(); err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
if err := sema.Post(); err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
}
Run Code Online (Sandbox Code Playgroud)
现在该程序本机编译(linux/amd64),我的问题是当我尝试交叉编译linux/arm(Ti am3352)时.
以前我所要做的就是:
GOOS=linux GOARCH=arm GOARM=7 CGO_ENABLED=1 CC=/am335x_toolchain/bin/armv7l-timesys-linux-gnueabi-gcc go build
Run Code Online (Sandbox Code Playgroud)
现在出现以下错误:
# runtime/cgo
/tmp/go-build820923984/runtime/cgo/_obj/_cgo_export.c:2:20: fatal error: stdlib.h: No such file or …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用libcheck构建一个简单的示例,但在使用 pkg-config 报告的标志时无法构建。
我的文件:tests/test.c
#include <stdlib.h>
#include <check.h>
START_TEST(zero)
{
int z = 0;
ck_assert_int_eq(0, z);
}
END_TEST
Suite* suite_zero(void)
{
Suite* s;
TCase* tc;
s = suite_create("suite_zero");
tc = tcase_create("zero");
tcase_add_test(tc, zero);
suite_add_tcase(s, tc);
return s;
}
int main(void)
{
int number_failed;
SRunner* sr;
Suite* s_zero = suite_zero();
sr = srunner_create(s_zero);
srunner_run_all(sr, CK_NORMAL);
number_failed = srunner_ntests_failed(sr);
srunner_free(sr);
return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
Run Code Online (Sandbox Code Playgroud)
我的系统:
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04 LTS"
$ …Run Code Online (Sandbox Code Playgroud) 在Rust指南之后,我想运行第8节和第9节中的示例.
enum MOrdering {
MLess,
MEqual,
MGreater,
}
fn cmp(a: int, b: int) -> MOrdering {
if a < b { MLess }
else if a > b { MGreater }
else { MEqual }
}
fn main() {
let x = 5i;
let y = 3i;
match cmp(x, y) {
MLess => println!("less"),
MGreater => println!("greater"),
MEqual => println!("equal"),
}
}
Run Code Online (Sandbox Code Playgroud)
这不会编译,它似乎与重命名枚举的示例相同,以确保它不与core :: cmp :: Ordering冲突.
这些是我在编译时得到的错误:
rustc src/main.rs
src/main.rs:8:16: 8:21 error: unresolved name `MLess`. Did you mean `a`? …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 lxc-create (v2.0.5) 创建一个容器。我没有安装 gpg 也不想安装它(嵌入式系统,没有 GPLv3)。我已经尝试过该--no-validate选项,但 lxc-create 表示它不存在,但它在帮助打印输出中将其显示为一个选项。有任何想法吗?
# lxc-create -t download -n main --no-validate
lxc-create: unrecognized option '--no-validate'
Usage: lxc-create --name=NAME --template=TEMPLATE [OPTION...]
lxc-create creates a container
Options :
-n, --name=NAME NAME of the container
-f, --config=CONFIG Initial configuration file
-t, --template=TEMPLATE Template to use to setup container
-B, --bdev=BDEV Backing store type to use
--dir=DIR Place rootfs directory under DIR
Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding …Run Code Online (Sandbox Code Playgroud)