修复Windows编译问题

This commit is contained in:
2025-03-06 16:07:47 +08:00
parent c1e666ce5b
commit dc94573862
5 changed files with 98 additions and 98 deletions

View File

@ -2,18 +2,19 @@ cmake_minimum_required(VERSION 3.10.0)
project(ai-box VERSION 0.1.0 LANGUAGES C CXX) project(ai-box VERSION 0.1.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
if (POLICY CMP0091)
cmake_policy(SET CMP0091 NEW)
endif (POLICY CMP0091)
if(NOT DEFINED CMAKE_BUILD_TYPE) if(NOT DEFINED CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release) set(CMAKE_BUILD_TYPE Release)
endif() endif()
set(TARGET_INCLUDE_DIRS cxx)
set(TARGET_LINK_DIRS)
set(TARGET_LINK_LIBS)
set(COMMON_SOURCE_FILES)
set(NODE_SOURCE_FILES)
set(NODE_ADDON_FOUND OFF) set(NODE_ADDON_FOUND OFF)
include_directories(cxx)
# NodeJS # NodeJS
execute_process( execute_process(
COMMAND node ${CMAKE_SOURCE_DIR}/thirdpart/cmake-js-util.js --include COMMAND node ${CMAKE_SOURCE_DIR}/thirdpart/cmake-js-util.js --include
@ -50,9 +51,7 @@ if(CMAKE_JS_RESULT EQUAL 0)
message(STATUS "CMAKE_JS_SRC: ${CMAKE_JS_SRC}") message(STATUS "CMAKE_JS_SRC: ${CMAKE_JS_SRC}")
message(STATUS "CMAKE_JS_LIB: ${CMAKE_JS_LIB}") message(STATUS "CMAKE_JS_LIB: ${CMAKE_JS_LIB}")
message(STATUS "NODE_ADDON_API_DIR: ${NODE_ADDON_API_DIR}") message(STATUS "NODE_ADDON_API_DIR: ${NODE_ADDON_API_DIR}")
list(APPEND TARGET_INCLUDE_DIRS ${CMAKE_JS_INC} ${NODE_ADDON_API_DIR}) include_directories(${CMAKE_JS_INC} ${NODE_ADDON_API_DIR})
list(APPEND TARGET_LINK_LIBS ${CMAKE_JS_LIB})
list(APPEND COMMON_SOURCE_FILES ${CMAKE_JS_SRC})
set(NODE_ADDON_FOUND ON) set(NODE_ADDON_FOUND ON)
endif() endif()
endif() endif()
@ -60,7 +59,7 @@ if(NOT (CMAKE_JS_RESULT EQUAL 0))
message(FATAL_ERROR "cmake js config failed") message(FATAL_ERROR "cmake js config failed")
endif() endif()
# 新增Nodejs目标
function(add_node_targert TARGET_NAME SOURCE_FILES) function(add_node_targert TARGET_NAME SOURCE_FILES)
add_library(${TARGET_NAME} SHARED ${CMAKE_JS_SRC} ${SOURCE_FILES}) add_library(${TARGET_NAME} SHARED ${CMAKE_JS_SRC} ${SOURCE_FILES})
target_link_libraries(${TARGET_NAME} ${CMAKE_JS_LIB}) target_link_libraries(${TARGET_NAME} ${CMAKE_JS_LIB})
@ -68,7 +67,6 @@ function(add_node_targert TARGET_NAME SOURCE_FILES)
endfunction() endfunction()
# MNN # MNN
set(MNN_CMAKE_FILE ${CMAKE_SOURCE_DIR}/thirdpart/MNN/${CMAKE_BUILD_TYPE}/config.cmake) set(MNN_CMAKE_FILE ${CMAKE_SOURCE_DIR}/thirdpart/MNN/${CMAKE_BUILD_TYPE}/config.cmake)
if(EXISTS ${MNN_CMAKE_FILE}) if(EXISTS ${MNN_CMAKE_FILE})
@ -77,13 +75,9 @@ if(EXISTS ${MNN_CMAKE_FILE})
message(STATUS "MNN_INCLUDE_DIR: ${MNN_INCLUDE_DIR}") message(STATUS "MNN_INCLUDE_DIR: ${MNN_INCLUDE_DIR}")
message(STATUS "MNN_LIBS: ${MNN_LIBS}") message(STATUS "MNN_LIBS: ${MNN_LIBS}")
include_directories(${MNN_INCLUDE_DIRS}) include_directories(${MNN_INCLUDE_DIRS})
list(APPEND TARGET_INCLUDE_DIRS ${MNN_INCLUDE_DIR}) link_directories(${MNN_LIB_DIR})
list(APPEND TARGET_LINK_DIRS ${MNN_LIB_DIR})
list(APPEND TARGET_LINK_LIBS ${MNN_LIBS})
add_compile_definitions(USE_MNN) add_compile_definitions(USE_MNN)
set(USE_MNN ON) set(USE_MNN ON)
else()
message(WARNING "MNN not found")
endif() endif()
# OpenCV # OpenCV
@ -94,18 +88,13 @@ if(EXISTS ${OpenCV_CMAKE_FILE})
message(STATUS "OpenCV_INCLUDE_DIR: ${OpenCV_INCLUDE_DIR}") message(STATUS "OpenCV_INCLUDE_DIR: ${OpenCV_INCLUDE_DIR}")
message(STATUS "OpenCV_LIBS: ${OpenCV_LIBS}") message(STATUS "OpenCV_LIBS: ${OpenCV_LIBS}")
include_directories(${OpenCV_INCLUDE_DIRS}) include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
if(NODE_ADDON_FOUND) if(NODE_ADDON_FOUND)
add_node_targert(cv cxx/cv/node.cc) add_node_targert(cv cxx/cv/node.cc)
target_link_libraries(cv ${OpenCV_LIBS}) target_link_libraries(cv ${OpenCV_LIBS})
target_link_directories(cv PUBLIC ${OpenCV_INCLUDE_DIR})
target_compile_definitions(cv PUBLIC USE_OPENCV) target_compile_definitions(cv PUBLIC USE_OPENCV)
endif() endif()
list(APPEND TARGET_INCLUDE_DIRS ${OpenCV_INCLUDE_DIR})
list(APPEND TARGET_LINK_DIRS ${OpenCV_LIB_DIR})
list(APPEND TARGET_LINK_LIBS ${OpenCV_LIBS})
list(APPEND NODE_SOURCE_FILES cxx/cv/node.cc)
endif() endif()
# OnnxRuntime # OnnxRuntime
@ -115,34 +104,19 @@ if(EXISTS ${ONNXRuntime_CMAKE_FILE})
message(STATUS "ONNXRuntime_LIB_DIR: ${ONNXRuntime_LIB_DIR}") message(STATUS "ONNXRuntime_LIB_DIR: ${ONNXRuntime_LIB_DIR}")
message(STATUS "ONNXRuntime_INCLUDE_DIR: ${ONNXRuntime_INCLUDE_DIR}") message(STATUS "ONNXRuntime_INCLUDE_DIR: ${ONNXRuntime_INCLUDE_DIR}")
message(STATUS "ONNXRuntime_LIBS: ${ONNXRuntime_LIBS}") message(STATUS "ONNXRuntime_LIBS: ${ONNXRuntime_LIBS}")
list(APPEND TARGET_INCLUDE_DIRS ${ONNXRuntime_INCLUDE_DIR}) include_directories(${ONNXRuntime_INCLUDE_DIR})
list(APPEND TARGET_LINK_DIRS ${ONNXRuntime_LIB_DIR}) link_directories(${ONNXRuntime_LIB_DIR})
list(APPEND TARGET_LINK_LIBS ${ONNXRuntime_LIBS})
if(NODE_ADDON_FOUND) if(NODE_ADDON_FOUND)
add_node_targert(ort cxx/ort/node.cc) add_node_targert(ort cxx/ort/node.cc)
target_link_libraries(ort ${ONNXRuntime_LIBS}) target_link_libraries(ort ${ONNXRuntime_LIBS})
target_link_directories(ort PUBLIC ${ONNXRuntime_LIB_DIR})
target_compile_definitions(ort PUBLIC USE_ONNXRUNTIME) target_compile_definitions(ort PUBLIC USE_ONNXRUNTIME)
endif() endif()
list(APPEND NODE_SOURCE_FILES
cxx/ort/node.cc
)
else()
message(WARNING "ONNXRuntime not found")
endif() endif()
include_directories(${TARGET_INCLUDE_DIRS}) if(MSVC)
link_directories(${TARGET_LINK_DIRS}) set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
add_library(addon SHARED ${COMMON_SOURCE_FILES} ${NODE_SOURCE_FILES} cxx/node.cc)
target_link_libraries(addon ${TARGET_LINK_LIBS})
set_target_properties(addon PROPERTIES PREFIX "" SUFFIX ".node")
# add_executable(test ${COMMON_SOURCE_FILES} cxx/test.cc)
# target_link_libraries(test ${TARGET_LINK_LIBS})
if(MSVC AND CMAKE_JS_NODELIB_DEF AND CMAKE_JS_NODELIB_TARGET)
execute_process(COMMAND ${CMAKE_AR} /def:${CMAKE_JS_NODELIB_DEF} /out:${CMAKE_JS_NODELIB_TARGET} ${CMAKE_STATIC_LINKER_FLAGS}) execute_process(COMMAND ${CMAKE_AR} /def:${CMAKE_JS_NODELIB_DEF} /out:${CMAKE_JS_NODELIB_TARGET} ${CMAKE_STATIC_LINKER_FLAGS})
endif() endif()

View File

@ -1,65 +1,65 @@
#include <unistd.h> // #include <unistd.h>
#include <napi.h> // #include <napi.h>
#include "cv/node.h" // #include "cv/node.h"
#ifdef USE_ORT // #ifdef USE_ORT
#include "ort/node.h" // #include "ort/node.h"
#endif // #endif
using namespace Napi; // using namespace Napi;
class TestWork : public AsyncWorker // class TestWork : public AsyncWorker
{ // {
public: // public:
TestWork(const Napi::Function &callback, int value) : Napi::AsyncWorker(callback), val_(value) {} // TestWork(const Napi::Function &callback, int value) : Napi::AsyncWorker(callback), val_(value) {}
~TestWork() {} // ~TestWork() {}
void Execute() // void Execute()
{ // {
printf("the worker-thread doing! %d \n", val_); // printf("the worker-thread doing! %d \n", val_);
sleep(3); // sleep(3);
printf("the worker-thread done! %d \n", val_); // printf("the worker-thread done! %d \n", val_);
} // }
void OnOK() // void OnOK()
{ // {
Callback().Call({Env().Undefined(), Number::New(Env(), 0)}); // Callback().Call({Env().Undefined(), Number::New(Env(), 0)});
} // }
private: // private:
int val_; // int val_;
}; // };
Value test(const CallbackInfo &info) // Value test(const CallbackInfo &info)
{ // {
// ai::ORTSession(nullptr, 0); // // ai::ORTSession(nullptr, 0);
// Function callback = info[1].As<Function>(); // // Function callback = info[1].As<Function>();
// TestWork *work = new TestWork(callback, info[0].As<Number>().Int32Value()); // // TestWork *work = new TestWork(callback, info[0].As<Number>().Int32Value());
// work->Queue(); // // work->Queue();
return info.Env().Undefined(); // return info.Env().Undefined();
} // }
Object Init(Env env, Object exports) // Object Init(Env env, Object exports)
{ // {
//OpenCV // //OpenCV
NODE_INIT_OBJECT(cv, InstallOpenCVAPI); // NODE_INIT_OBJECT(cv, InstallOpenCVAPI);
//OnnxRuntime // //OnnxRuntime
#ifdef USE_ORT // #ifdef USE_ORT
NODE_INIT_OBJECT(ort, InstallOrtAPI); // NODE_INIT_OBJECT(ort, InstallOrtAPI);
#endif // #endif
Napi::Number::New(env, 0); // Napi::Number::New(env, 0);
#define ADD_FUNCTION(name) exports.Set(Napi::String::New(env, #name), Napi::Function::New(env, name)) // #define ADD_FUNCTION(name) exports.Set(Napi::String::New(env, #name), Napi::Function::New(env, name))
// ADD_FUNCTION(facedetPredict); // // ADD_FUNCTION(facedetPredict);
// ADD_FUNCTION(facedetRelease); // // ADD_FUNCTION(facedetRelease);
// ADD_FUNCTION(faceRecognitionCreate); // // ADD_FUNCTION(faceRecognitionCreate);
// ADD_FUNCTION(faceRecognitionPredict); // // ADD_FUNCTION(faceRecognitionPredict);
// ADD_FUNCTION(faceRecognitionRelease); // // ADD_FUNCTION(faceRecognitionRelease);
// ADD_FUNCTION(getDistance); // // ADD_FUNCTION(getDistance);
#undef ADD_FUNCTION // #undef ADD_FUNCTION
return exports; // return exports;
} // }
NODE_API_MODULE(addon, Init) // NODE_API_MODULE(addon, Init)

View File

@ -3,6 +3,12 @@
#include <onnxruntime_cxx_api.h> #include <onnxruntime_cxx_api.h>
#include "node.h" #include "node.h"
#ifdef WIN32
#include <locale>
#include <codecvt>
#include <Windows.h>
#endif
using namespace Napi; using namespace Napi;
#define SESSION_INSTANCE_METHOD(method) InstanceMethod<&OrtSession::method>(#method, static_cast<napi_property_attributes>(napi_writable | napi_configurable)) #define SESSION_INSTANCE_METHOD(method) InstanceMethod<&OrtSession::method>(#method, static_cast<napi_property_attributes>(napi_writable | napi_configurable))
@ -168,7 +174,23 @@ class OrtSession : public ObjectWrap<OrtSession> {
: ObjectWrap(info) : ObjectWrap(info)
{ {
try { try {
if (info[0].IsString()) session_ = std::make_shared<Ort::Session>(env, info[0].As<String>().Utf8Value().c_str(), sessionOptions); if (info[0].IsString()) {
#ifdef WIN32
std::string str = info[0].As<String>().Utf8Value();
auto len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
wchar_t *buffer = new wchar_t[len + 1];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0';
std::wstring filename(buffer);
delete[] buffer;
// std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
// std::wstring filename = converter.from_bytes(info[0].As<String>().Utf8Value());
session_ = std::make_shared<Ort::Session>(env, filename.c_str(), sessionOptions);
#else
session_ = std::make_shared<Ort::Session>(env, info[0].As<String>().Utf8Value().c_str(), sessionOptions);
#endif
}
else if (info[0].IsTypedArray()) { else if (info[0].IsTypedArray()) {
size_t bufferBytes; size_t bufferBytes;
auto buffer = dataFromTypedArray(info[0], bufferBytes); auto buffer = dataFromTypedArray(info[0], bufferBytes);

View File

@ -127,9 +127,9 @@ async function testFaceAlign() {
async function test() { async function test() {
// testGenderTest(); await testGenderTest();
// testFaceID(); await testFaceID();
testFaceAlign(); await testFaceAlign();
} }
test().catch(err => { test().catch(err => {

View File

@ -104,6 +104,10 @@ async function downloadFromURL(name, url, resolver) {
fs.rmSync(outputDir, { force: true, recursive: true }); fs.rmSync(outputDir, { force: true, recursive: true });
if (!checkFile(saveName)) { if (!checkFile(saveName)) {
console.log(`开始下载${name}, 地址:${url}`);
await fetch(url).then(res => {
console.log(res.status)
})
const result = spawnSync("curl", ["-o", saveName + ".cache", "-L", url, "-s", "-w", "%{http_code}"], { ...spawnOption, stdio: "pipe" }); const result = spawnSync("curl", ["-o", saveName + ".cache", "-L", url, "-s", "-w", "%{http_code}"], { ...spawnOption, stdio: "pipe" });
assert(result.status == 0 && result.stdout.toString() == "200", `下载${name}失败`); assert(result.status == 0 && result.stdout.toString() == "200", `下载${name}失败`);
fs.renameSync(saveName + ".cache", saveName); fs.renameSync(saveName + ".cache", saveName);
@ -154,7 +158,7 @@ async function main() {
`set(MNN_LIBS MNN)`, `set(MNN_LIBS MNN)`,
].join("\n")); ].join("\n"));
//OpenCV //OpenCV
if (buildOptions.withOpenCV) cmakeBuildFromSource("OpenCV", "https://github.com/opencv/opencv.git", null, "4.11.0", [ if (buildOptions.withOpenCV) cmakeBuildFromSource("OpenCV", "https://github.com/opencv/opencv.git", "4.11.0", null, [
"-DBUILD_SHARED_LIBS=OFF", "-DBUILD_SHARED_LIBS=OFF",
"-DBUILD_opencv_apps=OFF", "-DBUILD_opencv_apps=OFF",
"-DBUILD_opencv_js=OFF", "-DBUILD_opencv_js=OFF",