问题
I am trying to develop in the cgo a plug-in of sudo.
https://www.sudo.ws/man/1.8.15/sudo_plugin.man.html
export the struct to the global scope of policy_plugin.
A policy plugin must declare and populate a
policy_plugin
struct in the global scope.
Do you have an explanation of what that means?
export_test.go
package main
/*
#include "sudo_plugin.h"
#include <stddef.h>
*/
import "C"
func main() {
}
// don't worked
//export policy
var policy = &C.struct_policy_plugin{
C.SUDO_POLICY_PLUGIN,
C.SUDO_API_VERSION,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
}
回答1:
It appears buildmode c-shared
only exports function entries, not variables.
While the design doc does not state this explicitly, it does not talk about variables explicitly either.
The cmd/cgo manual also does not mention variables explicitly but seems to imply that the special //export ...
comments apply to functions only.
What you could supposedly do about this is declare your external variable on the C side—after defining and expoting the necessary Go functions, like this:
"callbacks.go":
package main
import "C"
//export real_fn
func real_fn(x C.int) C.int {
return 42
}
"main.go":
package main
/*
typedef struct {
int x;
int (*fn) (int x);
} foo;
extern int real_fn(int);
foo xyzzy = {
0,
real_fn,
};
*/
import "C"
func main() {
}
Now after running go build -buildmode=c-shared
you can explore the generated library and see the xyzzy
symbol available there:
cshared% nm -g cshared | grep -E 'xyzzy|real_fn'
0000000000061330 T _cgoexp_4f8dd74b8333_real_fn
00000000000b42c0 T real_fn
00000000003274d0 D xyzzy
A note: if you're about using callbacks you have to put them into a separate file (or files)—this appears to be a quirk of cgo
.
来源:https://stackoverflow.com/questions/36212246/golang-cgo-cant-export-variables-by-build-mode-c-shared