興味本位でGo言語に触れてみようと思う。Linuxのshared libraryを呼び出してみる。
では、まずshared libraryを作るんだけど、以前作ったkeeloqでやってみる。こちら(https://sunday-engineer.jimdofree.com/2023/09/08/keeloq%E3%82%92%E9%A1%8C%E6%9D%90%E3%81%ABlinux%E5%85%B1%E6%9C%89%E3%83%A9%E3%82%A4%E3%83%96%E3%83%A9%E3%83%AA/)。
まぁそれは出来るっていう体で
mkdir callshared
cd callshared
mkdir keeloq
cd keeloq
で、こちらにkeeloqのshared libraryを作って、で、念のため、Cからcallしてみる。
keeloq_call.c
- #include <stdio.h>
- #include <stdint.h>
- #include <dlfcn.h>
- typedef uint32_t (*keeloq_enc_type)(uint32_t pr,uint64_t kr);
- typedef uint32_t (*keeloq_dec_type)(uint32_t cr,uint64_t kr);
- void* dll;
- keeloq_enc_type keeloq_enc;
- keeloq_dec_type keeloq_dec;
-
- int main(int argc,char** argv){
- uint32_t pr=0xf741e2db;
- uint64_t kr=0x5cec6701b79fd949;
- uint32_t cr;
- dll=dlopen("./libkeeloq.so",RTLD_LAZY);
- keeloq_enc=(keeloq_enc_type)dlsym(dll,"keeloq_enc");
- keeloq_dec=(keeloq_dec_type)dlsym(dll,"keeloq_dec");
-
- cr=keeloq_enc(pr,kr);
- printf("%08X\n",cr);
- pr=keeloq_dec(cr,kr);
- printf("%08X\n",pr);
- return 0;
- }
gcc keeloq.c
./a.out
まぁ、うまくいきます。
では、
cd ..
で、Goのコードを書く。
ちなみに、treeするとこういう状態。(pythonのテストコードとかもあったりする;)
- callshared
- ├── callshared.go
- └── keeloq
- ├── Makefile
- ├── a.out
- ├── keeloq.c
- ├── keeloq.o
- ├── keeloq_call.c
- ├── keeloq_call.py
- ├── libkeeloq.map
- └── libkeeloq.so
callshared.go
- package main
-
- /*
- #cgo LDFLAGS: -ldl
- #include <dlfcn.h>
- #include <stdint.h>
- uint32_t call_func(void* p,uint32_t a,uint64_t b){
- uint32_t (*func)(uint32_t a, uint64_t b) = p;
- return func(a, b);
- }
- */
- import "C"
- import "fmt"
- func main() {
- var pr C.uint32_t
- var cr C.uint32_t
- var kr C.uint64_t
- pr = 0xf741e2db
- kr = 0x5cec6701b79fd949
- dll := C.dlopen(C.CString("./keeloq/libkeeloq.so"), C.RTLD_LAZY)
- if dll == nil {
- panic("Failed to open shared object.")
- }
- defer C.dlclose(dll) //<--これ意味わからんのよね
- keeloq_enc := C.dlsym(dll, C.CString("keeloq_enc"))
- if keeloq_enc == nil {
- panic("Could not found function pointer.")
- }
- keeloq_dec := C.dlsym(dll, C.CString("keeloq_dec"))
- if keeloq_dec == nil {
- panic("Could not found function pointer.")
- }
- cr = C.call_func(keeloq_enc, pr, kr)
- fmt.Printf("%08X\n", cr)
- pr = C.call_func(keeloq_dec, cr, kr)
- fmt.Printf("%08X\n", pr)
- }
で、
go run callshared.go
って感じで、Cでやった結果とおんなじになりました。
いきなりshared libraryをcallするってGoやる気あるんか?って?、、、うむぅ
0 件のコメント:
コメントを投稿