This requires the library to work in real time.
I’m developing a certain library.
Define the function after the library has been compiled
Then call the function without recompiling
Normally you will get undefined
I just can’t get it to recompile.
I’d appreciate it if you could tell me how to rename the function every time I run example, or how to do it without recompiling.
------------- Before compiling -------------
//main.go
package main
import "example"
func main{
example.Error()//
}
// example
package example
------------- After compiling -------------
//main.go
package main
import "example"
func main{
example.Error()
}
// example
package example
func Error(){
panic("Error")
}
It sounds like you’re trying to compile code that calls a function that doesn’t exist and then somehow generate a function and call it at runtime. You could do this with the plugin package, but because you’re calling at runtime, you need to add some “boilerplate” in order to use it like example.Error():
package example
var Error func()
func init() {
pkg, err := plugin.Open("exampleimpl.so")
if err != nil {
panic(err)
}
f, err := pkg.Lookup("Error")
if err != nil {
panic(err)
}
Error = f.(func())
}
Then you generate your exampleimpl.go code and compile it with go build -buildmode=plugin to get an exampleimpl.so and then you run your main program that uses it. Note that this only works on *nix platforms, so if you’re on Windows, you’re out of luck.
I’m not sure what you mean about renaming, though. Can you reword the question?
So when I hear " how to rename the function every time I run example," I think the first time, you have a function Error and then the second time, you want it to be renamed to Error2 and then the third time, it should be renamed Error3, etc. You could do this with a go:generate program, but why would you want to do that?
Why do you want to do this? It will require rewriting the cgo command (link to source code) and if the code that your own cgo command creates is at all different from the code that Go’s own cgo command creates, you’ll need to modify the runtime package (link) to handle those differences.