1 回答

TA貢獻1831條經驗 獲得超10個贊
我通過創建 C 包裝頭文件來解決這個問題。然后我創建了一個 CPP 文件,它將所述 C 接口與庫 CPP 標頭和庫橋接起來。
C 標頭將我的庫對象理解為 void 指針,并且我的 CPP 實現必須對其進行強制轉換才能訪問其所有函數。
這extern "C"部分非常重要,可以防止 Go 崩潰——它可以防止 CPP 編譯器修改函數名稱。
當然,還要將二進制文件鏈接到正確的 LDFLAGS。
鳳凰.h
typedef void CTalon;
#ifdef __cplusplus
extern "C" {
#endif
CTalon* CTRE_CreateTalon(int port);
void CTRE_Set(CTalon* talon, double output);
void CTRE_Follow(CTalon* slave, CTalon* master);
#ifdef __cplusplus
}
#endif
鳳凰.cpp
#include "phoenix.h" // My C wrapper header
#include "ctre/phoenix/motorcontrol/can/TalonSRX.h" // Actual CPP header from library
#define TALON(ctalon) ((ctre::TalonSRX*) ctalon) // Helper macro to make converting to library object easier. Optional
namespace ctre { // Specific to my library which has a lot of long namespaces. Unrelated to problem
using ctre::phoenix::motorcontrol::ControlMode;
using ctre::phoenix::motorcontrol::can::TalonSRX;
}
extern "C" {
CTalon* CTRE_CreateTalon(int port) {
return (CTalon*) new ctre::TalonSRX(port);
}
void CTRE_Set(CTalon* talon, double output) {
TALON(talon)->Set(ctre::ControlMode::PercentOutput, output);
}
void CTRE_Follow(CTalon* slave, CTalon* master) {
TALON(slave)->Follow(*(TALON(master)));
}
}
- 1 回答
- 0 關注
- 286 瀏覽
添加回答
舉報