如何在golang中创建一个缓冲区以传递给C的dll函数?

huangapple go评论159阅读模式
英文:

How does golang create a buffer to pass to a C dll function?

问题

我需要从golang调用一个来自dll的C API。问题是C函数需要一个缓冲区,如何在golang中创建这个缓冲区,然后我可以将缓冲区传递给C函数?

void fooGetString(char* buffer, int buffer length)
英文:

I need to invoke a C API from golang, which is from a dll.
The problem is the C func need a buffer, how to create the
buffer in golang, then i can pass the buffer to the C func?

void fooGetString(char* buffer, int buffer length)

答案1

得分: 6

这样应该可以工作:

s := make([]byte, 256)
C.fooGetString((*C.char)(unsafe.Pointer(&s[0])), C.int(len(s)))
英文:

Something like this should work:

s := make([]byte, 256)
C.fooGetString((*C.char)(unsafe.Pointer(&s[0])), C.int(len(s)))

答案2

得分: 5

package main

// #include <string.h>
// void foo(char *s, int len) {
// strncpy(s, "foo", len);
// }
import "C"

import "fmt"
import "unsafe"

func main() {
buf := make([]byte, 256)
C.foo((*C.char)(unsafe.Pointer(&buf[0])), C.int(len(buf)))
fmt.Println(string(buf))
}

Output:

foo
英文:
package main

// #include &lt;string.h&gt;
// void foo(char *s, int len) {
//     strncpy(s, &quot;foo&quot;, len);
// }
import &quot;C&quot;

import &quot;fmt&quot;
import &quot;unsafe&quot;

func main() {
    buf := make([]byte, 256)
    C.foo((*C.char)(unsafe.Pointer(&amp;buf[0])), C.int(len(buf)))
    fmt.Println(string(buf))
}

Output:

foo

huangapple
  • 本文由 发表于 2012年4月21日 23:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/10260555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定