Home >Backend Development >Golang >How to call a C function that modifies go memory?

How to call a C function that modifies go memory?

WBOY
WBOYforward
2024-02-05 22:36:031224browse

How to call a C function that modifies go memory?

Question content

Suppose I have a signed C function

// myclib.h

void modify(double* ptr, int N);

This will change the memory pointed to by the parameter pointer ptr.

Is the following code safe for Go's garbage collector? Do you need runtimer.Pinner?

package main

// #cgo CFLAGS: -g -Wall
// #include "myclib.h"
import "C"
import (
    "fmt"
    "runtime"
)

func modifyWrapper(v []float64) {
    ptr := (*C.double)(&v[0])
    N := (C.int)(len(v))

    pinner := runtime.Pinner{}
    pinner.Pin(ptr)
    C.modify(ptr, N)
    pinner.Unpin()
}

func main() {
    v := []float64{9.0, 2.0, 1.0, 4.0, 5.0}
    modifyWrapper(v)
}

Correct answer


package main

/*
#cgo CFLAGS: -g -Wall
#include <stdio.h>
void modify(double* ptr, int N) {
    if (!ptr || N <= 0) {
        return;
    }
    printf("modify: %g %d\n", *ptr, N);
    *ptr = 42;
    printf("modify: %g %d\n", *ptr, N);
}
*/
import "C"

import (
    "fmt"
    "unsafe"
)

func modify(v []float64) {
    ptr := (*C.double)(unsafe.SliceData(v))
    N := (C.int)(len(v))
    C.modify(ptr, N)
}

func main() {
    v := []float64{9.0, 2.0, 1.0, 4.0, 5.0}
    fmt.Println(v)
    modify(v)
    fmt.Println(v)
}
[9 2 1 4 5]
modify: 9 5
modify: 42 5
[42 2 1 4 5]

The above is the detailed content of How to call a C function that modifies go memory?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete