This commit is contained in:
76
src/index.ts
Normal file
76
src/index.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { CString, dlopen, FFIType, JSCallback, suffix, type Pointer } from "bun:ffi";
|
||||
|
||||
const libPath = `libwcocr.${suffix}`;
|
||||
|
||||
const WechatOCR = dlopen(libPath, {
|
||||
wechat_ocr: {
|
||||
args: [
|
||||
FFIType.cstring, // ocr_exe路径
|
||||
FFIType.cstring, // wechat_dir路径
|
||||
FFIType.cstring, // imgfn路径
|
||||
FFIType.function, // 回调函数指针
|
||||
],
|
||||
returns: FFIType.bool, // 返回布尔值
|
||||
},
|
||||
stop_ocr: {
|
||||
args: [],
|
||||
returns: FFIType.void, // 无返回值
|
||||
},
|
||||
});
|
||||
|
||||
// 主函数
|
||||
async function callWechatOcr(
|
||||
ocrExe: string,
|
||||
wechatDir: string,
|
||||
imgfn: string
|
||||
): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 创建回调函数
|
||||
const callback = new JSCallback(
|
||||
(argPtr: Pointer) => {
|
||||
const arg = new CString(argPtr).toString();
|
||||
resolve(arg);
|
||||
callback.close(); // 释放回调
|
||||
},
|
||||
{
|
||||
args: [FFIType.ptr],
|
||||
returns: FFIType.void,
|
||||
}
|
||||
);
|
||||
|
||||
// 调用wechat_ocr函数
|
||||
const result = WechatOCR.symbols.wechat_ocr(
|
||||
Buffer.from(ocrExe + "\0"), // 转换为C字符串
|
||||
Buffer.from(wechatDir + "\0"),
|
||||
Buffer.from(imgfn + "\0"),
|
||||
callback // 直接传递JSCallback实例
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
callback.close();
|
||||
reject(new Error("OCR调用失败"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// 请在这里替换为你的实际路径
|
||||
const ocrExe = "/opt/wechat/wxocr";
|
||||
const wechatDir = "/opt/wechat";
|
||||
const imgfn = "/home/imbytecat/Pictures/Screenshots/Screenshot_07-Jul_10-00-20_9907.png";
|
||||
|
||||
console.log("OCR开始...");
|
||||
try {
|
||||
const result = await callWechatOcr(ocrExe, wechatDir, imgfn);
|
||||
console.log("OCR结果:", result);
|
||||
} catch (error) {
|
||||
console.error("OCR错误:", error);
|
||||
} finally {
|
||||
// 清理资源
|
||||
WechatOCR.symbols.stop_ocr();
|
||||
console.log("OCR结束...");
|
||||
}
|
||||
}
|
||||
|
||||
// 运行主函数
|
||||
main();
|
||||
Reference in New Issue
Block a user