到目前為止,我沒有成功將 Haskell 庫鏈接到 Rust 專案。我有很多錯誤,最新的是recompile with -fPICfor ghc。
我設法獲得了動態鏈接的功能示例 - 但無法靜態鏈接它。
現在附上我當前的設定:
構建.rs
fn main() { println!("cargo:rustc-link-search=native=deps"); println!("cargo:rustc-link-lib=static=tesths"); }src/main.rs
extern "C" { pub fn addTwo(x: i32) -> i32; pub fn init(); pub fn fin(); } fn main() { println!("Hello, world!"); }src/haskell/Lib.hs
module Lib where import Foreign.C.Types addTwo :: CInt -> CInt addTwo = (2 ) foreign export ccall addTwo :: CInt -> CInt包裝器
#include <HsFFI.h> #ifdef __GLASGOW_HASKELL__ #include "Lib_stub.h" #endif #include <stdio.h> void init(void) { static char *argv[] = {"libhs.so", 0}, **argv_ = argv; static int argc = 1; hs_init(&argc, &argv_); } void fin(void) { hs_exit(); }
我用 編譯 #4 ghc -c -static -lHSrts -lffi cwrapper.c,得到cwrapper.o. 同樣,我編譯 #3ghc -c -static -fPIC -lffi Lib.hs并獲得目標代碼。
完成后,我會繼續使用ar rcs libtesths.a Lib.o cwrapper.o.
在cargo build:
note: /usr/bin/ld: deps/libtesths.a(Lib.o):(.text 0x29): undefined reference to `newCAF'
/usr/bin/ld: deps/libtesths.a(Lib.o):(.text 0x39): undefined reference to `stg_bh_upd_frame_info'
/usr/bin/ld: deps/libtesths.a(Lib.o):(.text 0x48): undefined reference to `base_ForeignziCziTypes_zdfNumCInt_closure'
/usr/bin/ld: deps/libtesths.a(Lib.o):(.text 0x4f): undefined reference to `stg_ap_p_info'
…
我有一種預感,libHSrts 由于某種原因沒有被靜態鏈接。
更新
我遵循了 Shepmaster 的建議并成功地制作了一個作業示例。但是我現在在與我的 rust exec 鏈接時遇到問題。
I used stack with ghc-options: -staticlib -stubdir . and c-sources: cwrapper.c to build. When I try to build the rust project with cargo rustc — -C relocation-model=static:
/usr/bin/ld: deps/liba.a(Type.o): in function `integerzmwiredzmin_GHCziIntegerziType_zdwplusBigNatWord_info'
(.text.integerzmwiredzmin_GHCziIntegerziType_zdwplusBigNatWord_info 0x128): undefined reference to `__gmpn_add_1'
/usr/bin/ld: deps/liba.a(Type.o): in function
`integerzmwiredzmin_GHCziIntegerziType_zdwminusBigNatWord_info'
(.text.integerzmwiredzmin_GHCziIntegerziType_zdwminusBigNatWord_info 0xdf): undefined reference to `__gmpn_sub_1'
/usr/bin/ld: deps/liba.a(Type.o): in function `integerzmwiredzmin_GHCziIntegerziType_complementInteger_info'
(.text.integerzmwiredzmin_GHCziIntegerziType_complementInteger_info 0x138): undefined reference to `__gmpn_sub_1'
/usr/bin/ld: deps/liba.a(Type.o): in function `integerzmwiredzmin_GHCziIntegerziType_zdwtimesBigNatWord_info'
(.text.integerzmwiredzmin_GHCziIntegerziType_zdwtimesBigNatWord_info 0x158): undefined reference to `__gmpn_mul_1'
There is also mention of a wrappers.o. Any help is appreciated.
uj5u.com熱心網友回復:
我一次編譯了 Haskell 庫和 C shim,傳遞了-staticlib標志:
ghc -c -staticlib Lib.hs cwrapper.c -o libtesths.a
然后我呼叫了函式:
extern "C" {
pub fn addTwo(x: i32) -> i32;
pub fn init();
pub fn fin();
}
fn main() {
unsafe {
init();
println!("{}", addTwo(40));
fin();
}
}
% cargo run -q
42
這在使用 GHC 8.10.7 的 Apple Silicon 處理器上的 macOS 12.0.1 上對我有用。
如果您使用的是 x86_64 Linux,則可能需要添加RUSTFLAGS='-C relocation-model=static'.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366338.html
