以下是我的代码,希望go能捕获c代码的进度
package main
/*
#cgo CFLAGS: -I/home/roroco/Downloads/go/test_cgo/submodule/test_cgo_cpp/include
#cgo LDFLAGS: -L/home/roroco/Downloads/go/test_cgo/submodule/test_cgo_cpp/cmake-build-debug -ltest_cgo -Wl,-rpath=/home/roroco/Downloads/go/test_cgo/submodule/test_cgo_cpp/cmake-build-debug
#include "test_cgo.h"
*/
import "C"
import (
"fmt"
"unsafe"
)
//export goProgressCallbackHandler
func goProgressCallbackHandler(progress C.uint32_t) {
fmt.Printf("Progress: %d%%\n", progress)
}
func main() {
C.simulateProgress(unsafe.Pointer(C.goProgressCallbackHandler))
}
test_cgo.h
#ifndef PROGRESS_H
#define PROGRESS_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Function prototype for the callback
typedef void (*progressCallback)(uint32_t);
// Function to simulate progress update in C++
void simulateProgress(void *fnHandle);
#ifdef __cplusplus
}
#endif
#endif // PROGRESS_H
test_cgo.cpp
#include "test_cgo.h"
extern "C" {
void simulateProgress(void *fnHandle) {
progressCallback cb = (progressCallback) fnHandle;
for (uint32_t i = 0; i <= 100; i += 10) {
cb(i); // Call the callback function with the current progress
}
}
}
cgo 抛出错误
# command-line-arguments
./test_cgo.go:20:36: could not determine kind of name for C.goProgressCallbackHandler
如何使cgo代码工作
我修复了它,我应该添加
extern void goProgressCallbackHandlerProxy(uint32_t progress);
以使 C.goProgressCallbackHandlerProxy
存在
以下是完整代码
package main
/*
#cgo CFLAGS: -I/home/roroco/Downloads/go/test_cgo/submodule/test_cgo_cpp/include
#cgo LDFLAGS: -L/home/roroco/Downloads/go/test_cgo/submodule/test_cgo_cpp/cmake-build-debug -ltest_cgo -Wl,-rpath=/home/roroco/Downloads/go/test_cgo/submodule/test_cgo_cpp/cmake-build-debug
#include "test_cgo.h"
// Define a proxy function to call the Go callback handler from C
extern void goProgressCallbackHandlerProxy(uint32_t progress);
*/
import "C"
import (
"fmt"
"unsafe"
)
//export goProgressCallbackHandlerProxy
func goProgressCallbackHandlerProxy(progress C.uint32_t) {
fmt.Printf("Progress: %d%%\n", uint32(progress))
}
func main() {
// Convert Go function to a C function pointer (void*)
callbackPointer := unsafe.Pointer(C.goProgressCallbackHandlerProxy)
// Call C++ function via CGO with the callback function pointer
C.simulateProgress(callbackPointer)
}