'Pointers to C functions from Go causing unexpected fault address
I am trying to use functions from a 3rd party C SDK in my GoLang code.
I have already successfully accomplished exactly what I need to do in C++ (for the same library), as so:
mLibrary = LoadLibraryW( L"SDK-Win64-Shipping" );
typedef EResult ( *InitFunc )( InitializeOptions* );
InitializeOptions initOpts = {
API_LATEST,
nullptr,
nullptr,
nullptr,
"Name",
"Version 1.2.3.4",
nullptr,
};
InitFunc mInitFunc = nullptr;
mInitFunc = reinterpret_cast<InitFunc>( GetProcAddress( mLibrary, CCP_STRINGIZE( Initialize ) ) );
EResult result = mInitFunc( &initOpts );
trying to recreate the same steps in Golang gives me this:
type InitFunc func(*InitializeOptions) eResult
type InitializeOptions struct {
ApiVersion int32
AllocateMemoryFunction unsafe.Pointer
ReallocateMemoryFunction unsafe.Pointer
ReleaseMemoryFunction unsafe.Pointer
ProductName string
ProductVersion string
Reserved unsafe.Pointer
}
func main() {
mLibrary, err := GetHandle("SDK-Linux-Shipping.so")
initOpts := InitializeOptions{API_LATEST, nil, nil,
nil, "Name",
"Version 1.2.3.4", nil}
sym := C.CString("Initialize")
defer C.free(unsafe.Pointer(sym))
C.dlerror()
p := C.dlsym(mLibrary.Handle, sym)
mInitFunc := *(*InitFunc)(unsafe.Pointer(&p))
ret := mInitFunc(&initOpts) //CRASH HERE
}
The last line crashes the program with this error:
unexpected fault address 0x0
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x80 addr=0x0 pc=0x48f8c3]
goroutine 1 [running]:
runtime.throw({0x4a9327?, 0xc000018030?})
/usr/local/go/src/runtime/panic.go:992 +0x71 fp=0xc0000c1d40 sp=0xc0000c1d10 pc=0x432931
runtime.sigpanic()
/usr/local/go/src/runtime/signal_unix.go:825 +0x305 fp=0xc0000c1d90 sp=0xc0000c1d40 pc=0x4464a5
main.main()
/tmp/871cf058-c0e6-499b-8627-cf01aa55d09d/main.go:151 +0x383 fp=0xc0000c1f80 sp=0xc0000c1d90 pc=0x48f8c3
runtime.main()
/usr/local/go/src/runtime/proc.go:250 +0x212 fp=0xc0000c1fe0 sp=0xc0000c1f80 pc=0x435052
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:1571 +0x1 fp=0xc0000c1fe8 sp=0xc0000c1fe0 pc=0x45dce1
I know for sure that
- no errors are thrown at ay point preceding this
- mLibrary and mInitFunc are not nil
- The code compiles
Why am I seeing this error message?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
