Calling a DLL Function Syscall with mem-aligned parameters

Hello everyone,

I’m currently facing a problem while porting the embree api to go.
I’m using the syscall.LoadLibrary and syscall.Syscall functions instead of CGO

However I really don’t know how to tell GO to align the structures that are given as parameters to the functions on a 16-byte boundry. It seems that GO has no annotations telling the compiler to always lay down a type at a user defined memory alignment. Because of that I would have to choose one of two workarounds:

  1. Write a Call-Wrapper-Function in CGO and copy the unaligned structure to an aligned one before calling the DLL-Function
    -> Slow when the function will be called often

  2. Create a GO Wrapper-function for C’s “aligned_alloc” and “free” in CGO and allocate every structure by that function
    -> Not captured by go’s garbage collector and therefore not very elegant

I’m still wondering how a language can be made for performance programming yet not giving you features like mem-aligned structures for external functions that use SSE or AVX Instructions

I’m curious if someone knows a better solution to that problem.

another possibility:

write a func (t Type) MarshalBinary() ([]byte, error) method that returns a slice of bytes aligned the way the DLL expects.

  • it’s slow (although perhaps not as slow as calling cgo)
  • it won’t easily work for structures holding pointers

but it’s (more) GC friendly.

Ok, after some experiments I could come up with a more or less elegant solution myself.
The solution:

func AlignedAlloc(alignment, size uint) unsafe.Pointer {
    mem := make([]byte, size + alignment)
    off := uint(uintptr(unsafe.Pointer(&mem[0])))
    return unsafe.Pointer(&mem[alignment - (off % alignment)])

type MyStruct struct {
    A, B, C, D uint32

func main() {
    tst := (*MyStruct)(AlignedAlloc(16, (uint)(unsafe.Sizeof(MyStruct{}))))
    tst.A = 1
    tst.B = 2
    tst.C = 3
    tst.D = 4

    fmt.Printf("[ %d %d %d %d ] address: %p", tst.A, tst.B, tst.C, tst.D, tst)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.