英文:
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 <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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论