I have already put a question about the access violation of the TensorFlow lite c++ API. No one answered it so far, I believe the error I made is with selecting the wrong header- and library files from the Bazel build.
The steps that I have done to get the Tensorflow Lite Header and Libraries are from Youtube Tutorial and from Tensorflow.
Get Required Python (for me Python 3.9.5)
Install required Packages locally
Install Bazel (for me 3.7.2) and MSYS2 (after installation run pacman -S git patch unzip) and add it to Path
Check VS Build Tools 2019 for C++ (I have VS 19 Community with MSVC v142 & Windows 10 SDK)
Download and Unzip Tensorflow Sources from Github (Release of 2.5.3)
Inside the Tensorflow Sources, use python .\configure.py to start configure the bazel build (I only used Yes for override eigen strong inline, the rest is kept on the default value)
The I opened GitBash cmd inside the tensorflow source bazel build -c opt //tensorflow/lite:tensorflowlite
After a successful build later I get the "bazel-bin", "bazel-out", "bazel-tensorflow-2.5.3" and "bazel-testlogs" folder.
I created the following folders tensorflow/include/tensorflow/lite & core and tensorflow/include/flatbuffers for the headers and finally the tensorflow/lib for the libraries.
I copied the tensorflowlite.dll & tensorflow.dll.if.lib from the build directory (tensorflow-2.5.3\bazel-bin\tensorflow\lite) into the tensorflow/lib directory together with the flatbuffers.lib (from tensorflow-2.5.3\bazel-bin\external\flatbuffers\src)
I copied the tensorflow-2.5.3\bazel-bin\external\flatbuffers\src_virtual_includes\flatbuffers\flatbuffers headers into the tensorflow/include/flatbuffers directory
I copied the tensorflow-2.5.3\tensorflow\lite and tensorflow-2.5.3\tensorflow\core from the original sources into the tensorflow/include/tensorflow/lite & core directory.
After those steps, I could create a new VS Project and add the created linker and include information. And created the following short example to read the input layer.
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
#define TFLITE_MINIMAL_CHECK(x) \
if (!(x)) \
{ \
fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \
exit(1); \
}
int main()
{
std::string filename = "C:/project/tflitetesting/models/classification/mobilenet_v1_1.0_224_quant.tflite";
std::unique_ptr<tflite::FlatBufferModel> model =
tflite::FlatBufferModel::BuildFromFile(filename.c_str());
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder builder(*model, resolver);
std::unique_ptr<tflite::Interpreter> interpreter;
builder(&interpreter);
TFLITE_MINIMAL_CHECK(interpreter->AllocateTensors() == kTfLiteOk);
printf("=== Pre-invoke Interpreter State ===\n");
tflite::PrintInterpreterState(interpreter.get());
interpreter->SetAllowFp16PrecisionForFp32(true);
interpreter->SetNumThreads(1);
// Get Input Tensor Dimensions
unsigned char* input = interpreter->typed_input_tensor<unsigned char>(0);
}
But I am still receiving the access violation exception inside interpreter.h at
const Subgraph& primary_subgraph() const {
return *subgraphs_.front(); // Safe as subgraphs_ always has 1 entry.
}
What am I doing wrong? I dont want to build the shared library since the target (Coral Edge) has direct access to those functions (ex. interpreter->typed_input_tensor<unsigned char>(0); too.
The thing is, you cannot Debug a Release (Optimized) version.
with the command bazel build -c opt //tensorflow/lite:tensorflowlite you will create an "Release" version of the dll's and lib's.
Therefore just apply bazel build -c dbg //tensorflow/lite:tensorflowlite to get the debug tflite c++ version.
Related
I tried to build mysql-connector-c++ from source to static library.
Referring the official spec here, I generated the Visual studio solution by the following command:
cmake -DMYSQL_DIR="E:\mysql-5.7.21-winx64" -DWITH_BOOST="E:\libs\boost_1_67_0_BUILDED" -DWITH_JDBC=ON -G "Visual Studio 15 2017 Win64" ../
Then, I opened the vs solution generated by cmake.Run build, got the two libs: mysqlcppconn8-static-mt.lib, mysqlcppconn-static-mt.lib, and copied them to my project.
When I built my project (also vs2017 version), I got the error:
mysqlcppconn-static-mt.lib(net_serv.obj) : error LNK2038: 检测到“_MSC_VER”的不匹配项: 值“1800”不匹配值“1900”(ActionProcessor.obj 中)
I am confused. They're all built in vs2017, and platform toolset are all set to "Visual Studio 2017 (v141)". I can't understand where 1800_MSC_VER has come from.
Here is what I did
Specs
Visual Studio 15, (2017)
x64
Static (.lib)
With static runtime (/MT)
Tools
CMAKE
Bison (In a folder without spaces)
Perl (ActiveState or Strawberry)
OpenSSL 1.0.2q.tar.gz
Add CMAKE, Bison and pearl to your system path
Check to see if you got all setup correctly
C:\>cmake --version
cmake version 3.9.6
C:\>bison --version
bison (GNU Bison) 2.4.1
C:\>m4 --version
m4 (GNU M4) 1.4.13
C:\>perl -version
This is perl 5, version 24, subversion 3 (v5.24.3)
Step 1: Build OpenSSL 1.0.x
Note: if you want to build OpenSSL 1.1.x steps will be a bit different
Extract to: C:\mysql-8.0.15\openssl-1.0.2q
Run: x64 Native Tools Command prompt for VS 2017
cd C:\mysql-8.0.15\openssl-1.0.2q
Release
perl Configure VC-WIN64A no-shared --openssldir=.\rel64
ms\do_win64a
nmake -f ms\nt.mak
nmake -f ms\nt.mak install
Debug
nmake -f ms\nt.mak clean
perl Configure debug-VC-WIN64A no-shared --openssldir=.\dbg64
ms\do_win64a
nmake -f ms\nt.mak
nmake -f ms\nt.mak install
Step 2: Build MySQL (Yes the actual database)
Extract to: C:\mysql-8.0.15
Run: x64 Native Tools Command prompt for VS 2017
cd C:\mysql-8.0.15\
cmake . -G "Visual Studio 15 2017 Win64" ^
-DWITH_BOOST=C:/mysql-8.0.15/boost ^
-DDOWNLOAD_BOOST=1 ^
-DBUILD_CONFIG=mysql_release ^
-DWITH_SSL=C:\mysql-8.0.15\openssl-1.0.2q\rel64 ^
-DLINK_STATIC_RUNTIME_LIBRARIES=1
Copy m4.exe to C:\mysql-8.0.15\sql\ this avoids any m4.exe errors during built
Open MySQL.sln and build for release x64
Copy binary_log_funcs.h and binary_log_types.h from mysql-8.0.15\libbinlogevents\export to mysql-8.0.15\include
The library should be located at:
Static release library: C:\mysql-8.0.15\archive_output_directory\Release\mysqlclient.lib
Step 3: Build MySQL Connector C++
Copy C:\mysql-8.0.15-dbg\archive_output_directory\Debug\mysqlclient.lib
to C:\mysql-8.0.15-dbg\lib\vs14
Run CMAKE GUI
Browse to the path of the MySQL Connector Project.
Click Configure, Select Visual studio 15 2017 Win64, native compilers
Tick BUILD_STATIC
Tick STATIC_MSVCRT
TICK WITH_JDBC
remove WIN_SSL_YASL from CONFIG_VARS
WITH_SSL = C:\mysql-8.0.15\openssl-1.0.2q\rel64
WITH_BOOST= C:\mysql-8.0.15\boost\boost_1_66_0
MYSQL_DIR=C:\mysql-8.0.15
Open MySQL_CONCPP.sln build for Release x64
The library is located at:
C:\mysql-connector-c++-8.0.15\jdbc\install\lib\mysqlcppconn-static-mt.lib
C:\mysql-connector-c++-8.0.15\Release\mysqlcppconn8-static-mt.lib
Step 4: Test it
Note: This test is for the JDBC style API. If you are not maintaining an existing application, use the new xdevapi API.
Create a new project and put the following in main.cpp
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#define STATIC_CONCPP
#define CONCPP_BUILD_STATIC
#define CPPCONN_PUBLIC_FUNC
#include <driver.h>
#include <connection.h>
#include <statement.h>
#include <exception.h>
sql::Driver *mDriver;
sql::Connection *mConnection;
int main() {
mDriver = get_driver_instance(); //or use: new MySQL_Driver()
try {
mConnection = mDriver->connect("host", "username", "password");
mConnection->close();
}catch(sql::SQLException& ex) {
std::cout << ex.what();
}
delete mConnection;
return 0;
}
Set: Linker > Input > Additional Dependecies:
libeay32.lib;mysqlclient.lib;mysqlcppconn8-static-mt.lib;mysqlcppconn-static-mt.lib;ssleay32.lib;%(AdditionalDependencies)
Set: Configuration Properties > VC++ Directories
Include Directories.
Library Directories.
I don't even know where to start explaining to be honest. Building this was a massive pain.
Before you begin to read this, please ensure you have the following:
C:\boost
C:\OpenSSL-Win32
C:\OpenSSL-Win64
Because I was writing my own "wrapper" and trying to make UNICODE work properly, I was getting weird exceptions, and I was unable to debug anything because I downloaded the latest package which is built without debug information (https://dev.mysql.com/downloads/connector/cpp/)
This is the first time I try to build this, so I went to their Github repository and grabbed the latest "master": https://github.com/mysql/mysql-connector-cpp
BUT! This does not contain the "JDBC" sources, which is by the way the "native" connector as they call it. So I grabbed it from the branch: https://github.com/mysql/mysql-connector-cpp/tree/jdbc and then copied the files into "mysql-connector-cpp-master\jdbc".
OK. I opened "x64 Native Tools Command Prompt for VS 2017" and navigated to "mysql-connector-cpp-master". At this point I still had no idea what I am doing and how to build it, all I could understand from the docs and different articles here is to run:
cmake -DWITH_JDBC=ON --build .
This started to configure things and build OK, but it stopped here:
-- Searching for static libraries with the base name(s) "mysqlclient"
CMake Error at FindMySQL.cmake:524 (message):
Could not find "mysql.h" from searching "/usr/include/mysql
/usr/local/include/mysql /opt/mysql/mysql/include
/opt/mysql/mysql/include/mysql /usr/local/mysql/include
/usr/local/mysql/include/mysql C:\Program Files/MySQL/*/include
C:/MySQL/*/include"
Call Stack (most recent call first):
CMakeLists.txt:332 (INCLUDE)
OK. So what now... where is "mysql.h" ?! After searching... and searching, I found this: Missing mysql.h and trying to find mysql-devel
And I quote:
Grab the MySQL Community Server and install it on your system. It
contains a directory called include in which you find the mysql.h.
Ok, great we need more stuff. So I download: https://dev.mysql.com/downloads/mysql/ and run the command again.
Happy days, something happened but no libs yet. I did get however a VS 2017 solution called: "MYSQLCPPCONN.sln".
This contains VS 2017 configuration to build the library for Win32. And of course trying to build with this solution will give you A LOT of unresolved external symbols.
So I run again the cmake but with static option added:
cmake -DWITH_JDBC=ON -DBUILD_STATIC=ON --build .
This time when I open "MYSQLCPPCONN.sln" I can see another project "mysqlcppconn-static" and this builds fine without issues.
However, in my case I need x64. I just created a new configuration for x64 by copying the exiting configuration fron Win32.
So that's it, I have both Win32 and x64 "mysqlcppconn-static.lib".
Overall Conclusion at this time:
Quite hard to build, without experience you will spend some time...
time.
No proper documentation, their existing documentation is poorly
written and very confusing.
No UNICODE support, yes the projects compile as Multi-Byte
Character Set.
I will see if I can debug and find out why am I getting exceptions in the library when using this (from their documentation):
sql::ConnectOptionsMap connection_properties;
connection_properties["hostName"] = "";
connection_properties["port"] = "";
connection_properties["userName"] = "";
connection_properties["password"] = "";
connection_properties["schema"] = "";
connection_properties["OPT_CONNECT_TIMEOUT"] = 10;
connection_properties["CLIENT_MULTI_STATEMENTS"] = (true);
connection_properties["OPT_CHARSET_NAME"] = "utf8";
connection_properties["OPT_SET_CHARSET_NAME"] = "utf8";
I hope you can build your library with this information, and hopefully in the future it will become more easier and clear.
Good Luck.
I am currently trying to use Tensorflow's shared library in a non-bazel project, so I creat a .so file from tensorflow using bazel.
but when I launch a c++ program that uses both Opencv and Tensorflow, it makes me the following error :
[libprotobuf FATAL external/protobuf/src/google/protobuf/stubs/common.cc:78] This program was compiled against version 2.6.1 of the Protocol Buffer runtime library, which is not compatible with the installed version (3.1.0). Contact the program author for an update. If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library. (Version verification failed in "/build/mir-pkdHET/mir-0.21.0+16.04.20160330/obj-x86_64-linux-gnu/src/protobuf/mir_protobuf.pb.cc".)
terminate called after throwing an instance of 'google::protobuf::FatalException'
what(): This program was compiled against version 2.6.1 of the Protocol Buffer runtime library, which is not compatible with the installed version (3.1.0). Contact the program author for an update. If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library. (Version verification failed in "/build/mir-pkdHET/mir-0.21.0+16.04.20160330/obj-x86_64-linux-gnu/src/protobuf/mir_protobuf.pb.cc".)
Abandon (core dumped)
Can you help me?
Thank you
You should rebuild TensorFlow with a linker script to avoid making third party symbols global in the shared library that Bazel creates. This is how the Android Java/JNI library for TensorFlow is able to coexist with the pre-installed protobuf library on the device (look at the build rules in tensorflow/contrib/android for a working example)
Here's a BUILD file that I adapted from the Android library to do this:
package(default_visibility = ["//visibility:public"])
licenses(["notice"]) # Apache 2.0
exports_files(["LICENSE"])
load(
"//tensorflow:tensorflow.bzl",
"tf_copts",
"if_android",
)
exports_files([
"version_script.lds",
])
# Build the native .so.
# bazel build //tensorflow/contrib/android_ndk:libtensorflow_cc_inference.so \
# --crosstool_top=//external:android/crosstool \
# --host_crosstool_top=#bazel_tools//tools/cpp:toolchain \
# --cpu=armeabi-v7a
LINKER_SCRIPT = "//tensorflow/contrib/android:version_script.lds"
cc_binary(
name = "libtensorflow_cc_inference.so",
srcs = [],
copts = tf_copts() + [
"-ffunction-sections",
"-fdata-sections",
],
linkopts = if_android([
"-landroid",
"-latomic",
"-ldl",
"-llog",
"-lm",
"-z defs",
"-s",
"-Wl,--gc-sections",
"-Wl,--version-script", # This line must be directly followed by LINKER_SCRIPT.
LINKER_SCRIPT,
]),
linkshared = 1,
linkstatic = 1,
tags = [
"manual",
"notap",
],
deps = [
"//tensorflow/core:android_tensorflow_lib",
LINKER_SCRIPT,
],
)
And the contents of version_script.lds:
{
global:
extern "C++" {
tensorflow::*;
};
local:
*;
};
This will make everything in the tensorflow namespace global and available through the library, while hiding the reset and preventing it from conflicting with protobuf.
(wasted a ton of time on this so I hope it helps!)
The error indicates that the program was complied using headers (.h files) from protobuf 2.6.1. These headers are typically found in /usr/include/google/protobuf or /usr/local/include/google/protobuf, though they could be in other places depending on your OS and how the program is being built. You need to update these headers to version 3.1.0 and recompile the program.
This is indeed a pretty serious problem! I get the below error similar to you:
$./ceres_single_test
[libprotobuf FATAL google/protobuf/stubs/common.cc:78] This program was compiled against version 2.6.1 of the Protocol Buffer runtime library, which is not compatible with the installed version (3.1.0). Contact the program author for an update. If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library. (Version verification failed in "/build/mir-pkdHET/mir-0.21.0+16.04.20160330/obj-x86_64-linux-gnu/src/protobuf/mir_protobuf.pb.cc".)
terminate called after throwing an instance of 'google::protobuf::FatalException'
Aborted
My workaround:
cd /usr/lib/x86_64-linux-gnu
sudo mkdir BACKUP
sudo mv libmirprotobuf.so* ./BACKUP/
Now, the executable under test works, cool. What is not cool, however, is that things like gedit no longer work without running from a shell that has the BACKUP path added to LD_LIBRARY_PATH :-(
Hopefully there's a better fix out there?
The error complains about the Protocol Buffer runtime library, which is not compatible with the installed version. This error is coming from the GTK3 library. GTK3 use Protocol Buffer 2.6.1. If you use GTK3 to support Opencv, you get this error. The easiest way to fix this, you can use QT instead of GTK3.
If you use Cmake GUI to install Opencv, just select QT support instead of using GTK3. You can install QT using the following command.
sudo apt install qtbase5-dev
rebuild libprotobuf with -Dprotobuf_BUILD_SHARED_LIBS=ON
then make install to cover the older version
I've built ICU 57.1 statically with MinGW x32;
As a result, I got the following files in the lib directory:
libsicudt.a
libsicuin.a
libsicuio.a
libsicule.a
libsiculx.a
libsicutest.a
libsicutu.a
libsicuuc.a
sicudt.a
sicudt.dll
Now I want to run one of the examples, but whatever I try it
I receive errors like
"undefined reference to unum_...
unum_setAttribute
unum_formatInt64
u_isspace".
Total number of errors at the beginning was about 1700.
Analyzing pkgconfig files I figured out some mutual dependencies and
after reordering .a files in cmd line reduced errors to 82.
But I have no idea where to go next.
Google shows that many people have same problem with ICU but
so far there is no solution that works for me and explains the cause.
When building, I use Qt Creator for convenience, here is my .pro file:
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp
ICUDIR=$$(ICU_PATH)
ICU_LIBPATH=$$ICUDIR"/dist/lib/"
INCLUDEPATH += $$ICUDIR"/dist/include"
LIBS += $$ICU_LIBPATH"libsicuuc.a" $$ICU_LIBPATH"libsicudt.a" \
$$ICU_LIBPATH"libsicuin.a" $$ICU_LIBPATH"libsicuio.a" \
$$ICU_LIBPATH"libsicule.a" $$ICU_LIBPATH"libsiculx.a" \
$$ICU_LIBPATH"libsicutu.a" $$ICU_LIBPATH"sicudt.a"
I have following questions:
1) Can anybody write a simple one line command that statically builds
the simpliest ICU app using g++? Is it even possible?
2) What is the correct order of .a files when passing them to linker?
3) What are files libsicudt.a, sicudt.a and sicudt.dll inteded for?
4) Is the file list I wrote above complete or my build is corrupt?
5) Is there anything I've missed of doing wrong?
Finally, I solved the problem. In order to share my experiece with you
I will describe four major pitfalls that I've encountered.
I assume that you use msys2 and MinGW-w32 if you want to repeat the steps.
Use same toolchain for everything. Note that MinGW, MinGW-w32 and MinGW-w64
are 3 different toolchains. If you have multiple installations of MinGW
like me, make sure that you use only one of them for the entire project.
I chose MinGW-w32 for compatibility reasons.
The newest versions of software often contain bugs, and they
require from you some more dancing with tambourins.
ICU v58 was buggy at the moment of writing this post.
The solution is to revert to an older version (57.1 in my case).
Before building ICU library, make sure to setup everything correctly.
Here problem is with using namespaces and renaming namespaces which
ICU does by default.
Find file C:\icu\source\common\unicode\uconfig.h and add the following
at the beginning after include guards:
#define U_DISABLE_RENAMING 1
#define U_USING_ICU_NAMESPACE 0
Save the file. Open MSYS2 terminal and set mingw-w32 as working toolset:
export PATH="/c/msys64/mingw32/bin:$PATH"
Go to icu/source dir:
cd /c/icu/source
Configure ICU for static build with no renaming and U_USING_ICU_NAMESPACE=0:
export CFLAGS="-DU_CHARSET_IS_UTF8=1 -DU_GNUC_UTF16_STRING=1 -DU_STATIC_IMPLEMENTATION"
export CXXFLAGS="-DU_USING_ICU_NAMESPACE=0 -std=gnu++11 -DU_CHARSET_IS_UTF8=1 -DU_GNUC_UTF16_STRING=1 -DU_HAVE_CHAR16_T=1 -DUCHAR_TYPE=char16_t -Wall --std=c++11 -DU_STATIC_IMPLEMENTATION" -static-libstdc++ -fno-exceptions
export CPPFLAGS="-DU_DISABLE_RENAMING=1 -DU_CHARSET_IS_UTF8=1 -DU_STATIC_IMPLEMENTATION"
export LDFLAGS="-std=gnu++11"
./runConfigureICU MinGW prefix=$PWD/../dist -enable-static -disable-shared --disable-renaming
Build and install ICU lib. -j4 speeds up the process if you have 4 cores:
mingw32-make -j4
mingw32-make install
Cleanup intermediate files:
mingw32-make clean
Now you should have static libraries located at icu/dist/lib .
PITFALL 4: when linking statically, you should pass libraries to
linker in correct order. That matters only for static linking.
But how to figure out which order is correct?
Here pkg-config tool comes handy.
What it does is the following: takes library package names as
parameter, calculates dependencies and returns the complete string
of parameters that can be fed directly to the compiler
or viewed by you to understand what's going on under the hood.
There are 5 packages located at C:\icu\dist\lib\pkgconfig.
Let's configure path for pkg-config:
export PKG_CONFIG_PATH="/c/icu/dist/lib/pkgconfig:$PKG_CONFIG_PATH"
In order to test it, type:
pkg-config --static --cflags --libs icu-uc icu-i18n icu-io icu-le icu-lx
The output should be:
-IC:/icu/dist/include -LC:/icu/dist/lib -lsicuio -lsicuin -lsiculx -lsicule -lsicuuc -lsicudt -lpthread -lm
That's the string we have to pass to compiler.
As final test, we will compile a simple example app using command line:
Create folder /c/icu/dist/test with file test.cpp inside:
#include <unicode/unistr.h>
#include <unicode/ustdio.h>
#include <unicode/brkiter.h>
#include <stdlib.h>
using namespace icu;
void printUnicodeString(UFILE *out, const UnicodeString &s) {
UnicodeString other = s;
u_fprintf(out, "\"%S\"", other.getTerminatedBuffer());
}
int main( void )
{
UFILE *out;
UErrorCode status = U_ZERO_ERROR;
out = u_finit(stdout, NULL, NULL);
if(!out) {
fprintf(stderr, "Could not initialize (finit()) over stdout! \n");
return 1;
}
ucnv_setFromUCallBack(u_fgetConverter(out), UCNV_FROM_U_CALLBACK_ESCAPE,
NULL, NULL, NULL, &status);
if(U_FAILURE(status)) {
u_fprintf(out, "Warning- couldn't set the substitute callback - err %s\n", u_errorName(status));
}
/* End Demo boilerplate */
u_fprintf(out,"ICU Case Mapping Sample Program\n\n");
u_fprintf(out, "C++ Case Mapping\n\n");
UnicodeString string("This is a test");
u_fprintf(out, "\nstring: ");
printUnicodeString(out, string);
string.toUpper(); /* string = "THIS IS A TEST" */
u_fprintf(out, "\ntoUpper(): ");
printUnicodeString(out, string);
return 0;
}
Go to the test dir:
cd /c/icu/dist/test
g++ -o test test.cpp \
`pkg-config --cflags --libs --static icu-uc icu-i18n icu-io icu-le icu-lx`
Run the app:
./test
Maybe this is not the best way to do,
especially concerning workspaces, but it works.
More about pgk-config here:
https://people.freedesktop.org/~dbn/pkg-config-guide.html
I am trying to use a custom node package that I wrote in an Electron application and I am having trouble getting the resulting DLL/Node package to initialize. When I launch my Electron application, I get the following error:
Uncaught Error: A dynamic link library (DLL) initialization routine failed.
The DLL being linked is a simple library written in C++ that has one function that takes a double as an input and simply adds one to it, returning the result. To build the C++ library, I use SWIG (http://www.swig.org/) and node-gyp with the following commands:
swig -c++ -javascript -node ./src/mace_api.i
node-gyp clean configure build
mace_api is the package I am trying to build. mace_api.i, the binding.gyp file, and the source files for my library are defined as follows:
mace_api.i
%module MaceAPI
%{
#include "./mace_api.cpp"
%}
%include <windows.i>
%include "./mace_api.h"
binding.gyp
{
"targets": [
{
"target_name": "mace-api",
"sources": [ "./src/mace_api_wrap.cxx" ]
}
]
}
mace_api.h
#ifndef MACE_API_H
#define MACE_API_H
#include <iostream>
#include <functional>
using namespace std;
class MaceAPI
{
public:
MaceAPI();
double addOne(double input);
};
#endif // MACE_API_H
mace_api.cpp
#include "mace_api.h"
MaceAPI::MaceAPI()
{
}
double MaceAPI::addOne(double input)
{
double ret = input + 1.0;
return ret;
}
SWIG takes the C++ source files and basically writes a wrapper that can be used, in this case, by node-gyp to build a Node package. Has anyone tried to use a custom Node module built in this manner in an Electron application? Am I missing something with how SWIG generates a wrapper for my C++ library, or how Electron handles custom Node packages? I am able to link the library with Node, but not with Electron. Any help would be appreciated.
For completeness, below is how I am trying to include and use my package in my Electron application:
var libMaceTest= require('mace-api/build/Release/mace-api');
var test = new libMaceTest.MaceAPI();
console.log(test.addOne(5));
Have you checked out https://github.com/electron/electron/blob/master/docs/tutorial/using-native-node-modules.md#manually-building-for-electron
Specifically,
Manually building for Electron
If you are a developer developing a native module and want to test it
against Electron, you might want to rebuild the module for Electron
manually. You can use node-gyp directly to build for Electron:
cd /path-to-module/ HOME=~/.electron-gyp node-gyp rebuild
--target=1.2.3 --arch=x64 --dist-url=https://atom.io/download/atom-shell
The HOME=~/.electron-gyp changes where to find development headers.
The
--target=1.2.3 is version of Electron. The --dist-url=... specifies where to download the headers. The --arch=x64 says the module is built
for 64bit system.
I followed this tutorial http://blog.ulf-wendel.de/?p=215#hello. I tried both on Visual C++ 2008 and Visual C++ 2010. Either static or dynamic, the compiler gave me the same exact error messages:
error LNK2001: unresolved external symbol _get_driver_instance
Has anyone experience this issue before?
Update:
+ Additional Dependencies: mysqlcppconn.lib
+ Additional Include Directories: C:\Program Files\MySQL\MySQL Connector C++ 1.0.5\include
+ Additional Libraries Directories: C:\Program Files\MySQL\MySQL Connector C++ 1.0.5\lib\opt
Another Update:
Click F12 on get_driver_instance() linked to:
class CPPCONN_PUBLIC_FUNC Driver
{
protected:
virtual ~Driver() {}
public:
// Attempts to make a database connection to the given URL.
virtual Connection * connect(const std::string& hostName, const std::string& userName, const std::string& password) = 0;
virtual Connection * connect(std::map< std::string, ConnectPropertyVal > & options) = 0;
virtual int getMajorVersion() = 0;
virtual int getMinorVersion() = 0;
virtual int getPatchVersion() = 0;
virtual const std::string & getName() = 0;
};
} /* namespace sql */
extern "C"
{
CPPCONN_PUBLIC_FUNC sql::Driver *get_driver_instance();
}
Apparently, the function existed, but the linker could not find it.
Code snippet:
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>
using namespace std;
#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
int main() {
try {
sql::Driver *driver;
sql::Connection *conn;
sql::Statement *stmt;
sql::ResultSet *res;
driver = get_driver_instance();
conn = driver->connect( "http://localhost/chandb", "root", "chan" );
stmt = conn->createStatement();
res = stmt->executeQuery( "select * from another" );
while( res->next() ) {
cout << "id = " << res->getInt( "Id" );
cout << "id = " << res->getInt( "GoldValue" );
cout << "id = " << res->getString( "Model" );
}
delete conn;
delete stmt;
delete res;
std::cout << "This is it";
}
catch( sql::SQLException e ) {
cout << e.what();
}
}
Thanks,
Chan
According to MySQL 5.1 Reference Manual if you are using the Version 1.1 of the MySQL Connector C++:
"get_driver_instance() is now only available in dynamic library builds - static builds do not
have this symbol. This was done to accommodate loading the DLL with LoadLibrary or dlopen. If you do not use CMake for building the source code you will need to define mysqlcppconn_EXPORTS if you are loading dynamically and want to use the get_driver_instance() entry point."
If I understand the previous note correctly, you have to use the dynamic build and define mysqlcppconn_EXPORTS.
If you use static linking, you need to set CPPCONN_PUBLIC_FUNC= in Project / Properties / C++ / Preprocessor / Preprocessor Definitions
I faced Same Error while using c++/Sql Connector.
and after spending entire day I solved this problem by using 32 bit libmysql.dll , 32 bit libmysqlcppcon.lib and 32 bit libmysqlcppcon.dll ( Dynamic binding is used because driver instance creation is only available in dynamic library of libmysqlcppcon.lib)
I found very good link explaining everything along with the working code. I think it would help others if they stuck at the same issue.
http://r3dux.org/2010/11/how-to-use-mysql-connectorc-to-connect-to-a-mysql-database-in-windows/
error LNK2001: unresolved external
symbol _get_driver_instance
That error message basically means that the linker cannot locate the function get_driver_instance anywhere, eg. it's not in any of the object files from your compilation units, not in a static .lib library or import library. This can also happen if the mangled names in the library doesn't match exactly with what the linker expects to find. eg. Library was built with different calling convention etc.
I would suggest that you take a look at the final command line being used from your project and update your post here for both compiling and linking. Second, make sure the mysql library you're linking against has that function. I believe there's a commandline tool in vs for dumping and viewing the contents of a static lib.
If you're linking against a dynamic dll version of mysql, make sure the import library contains the missing referenced symbol. Additionally, you can crack the dll open with a PE viewer and look under it's export tables to verify that that function actually exist and is visible.
Edit: According to this post, the function get_driver_instance should be in 'mysqlcppconn.lib' somewhere. Are you sure that file is being properly linked?
I read the article you mentioned.
It has this line for static compilation : As said, you need to link both "mysqlcppconn-static.lib" and "libmysql.lib".
Since you don't mention this is you question ,have you tried this ?
Also , on a forum I read this (for eclips) "You must have this in source":
#include "mysql_driver.h"
#include "mysql_connection.h"
using namespace sql::mysql;
Anyway ,good luck !
I don't know if you have your heart set on using this MySQL Connector/Driver package but there are many robust database wrappers available for free or nearly free out there if this is causing seemingly unspoken headaches for you.
I actually was thoroughly impressed by QT database objects when I used them previously for a data model project. The QT framework is licensed under LGPL and also has a commercial version available and is a very versatile set of cross platform libraries. The QtSql objects provide a consistent interface to many databases including MySql, SQLServer, Postgres, ODBC, etc with the ability to substitute your own drivers and still use the same interface for everything at a high level in C++
Some other notable options:
SQLApi++
MySQL++
Not trying to come on like a salesman or anything and I have no affiliation with any of these but sometimes it never hurts to shop around and find something that works better for your needs.
I solved using the 32bit version both for mysql server and connector/c++ on 64bit OS.
I think the problem are the boost libraries but im not sure.
I spent several hours trying to solve the problem exactly the same as you. I finally found out the problem myself. I downloaded the 64-bit version of MySQL/SQL Connector and followed a tutorial in MySQL.com in setting up win32 console project its properties and got the error message as mentioned. It was because the tutorial is teaching to build a 32-bit program. After I change to build a release version of X64 code, problem was solved.
Make sure your library is 32bit or 64bit and then configure your Visual Studio accordingly (in configuration manager).
Hello same problem for me, i have search and found my solution, i give you my paths on my local computer, but you can put all where you want, it's just my personnal notes:
The goal is to compile mysql cpp connector on your computer, to have lib which work on your computer when you compile somewhat with.
DEPENDENCIES:
clone (recursively with submodules, to have the folder jdbc) the repo on master branch (same than 8.0.27 for me when i write this post) of mysql cpp connector source code for windows on github:
https://github.com/mysql/mysql-connector-cpp/tree/master
Or if you haven't git, you can do it manualy by download zip: mysql-connector-c++-8.0.27-src.zip: https://dev.mysql.com/downloads/connector/cpp/
and download manualy jdbc by clicking on jdbc folder on this page: https://github.com/mysql/mysql-connector-cpp/tree/master
and the jdbc download must to be unzip and rename by "jdbc", and put in the mysql cpp connector folder
download mysql server for windows:
choice: Windows (x86, 64-bit), ZIP Archive
version: 8.0.27
size: 209.4M
url: https://dev.mysql.com/downloads/mysql/
filename: mysql-8.0.27-winx64
and put mysql-8.0.27-winx64 in C:\Users\< USER >\Downloads\mysql-8.0.27-winx64
download openssl (Win64 OpenSSL v1.1.1m):
binary installer msi: https://slproweb.com/products/Win32OpenSSL.html
it's not official :/ but that work (and it linked by this site too: https://wiki.openssl.org/index.php/Binaries), and i have failed and give up to build from source code)
Install openssl here: E:\OpenSSL-Win64
unfortunaly the version 3.0.1 doesn't work for build cpp connector (or my bad ?)
download boost: https://www.boost.org/users/download/
untarGz and put it here: E:\boost_1_78_0
CONFIGURATION:
for the configuration you must have this folder architecture:
. Parent Folder (for me it's E:\MySql)
|
|\
| \
| . _SOURCE (renamed mysql cpp connector repo)
| |
| .
| .
| .
| |
| |\
| | \
| | . jdbc (jdbc submodule)
| .
| .
| .
|
|\
| \
| . _BUILD
\
\
. _INSTALL
with this folder architecture if you have errors in next commands, your sources will not to be modify, you will have just to remove the containt of _BUILD and _INSTALL folders to relaunch
open powershell in E:\MySql and launch cmd:
cmake .\_SOURCE\ -B .\_BUILD\ -D CMAKE_INSTALL_PREFIX=.\_INSTALL -D CMAKE_BUILD_TYPE=Debug -D WITH_SSL="E:\OpenSSL-Win64" -D BUILD_STATIC=OFF -D WITH_JDBC=ON -D WITH_MYSQL="C:\Users\< USER >\Downloads\mysql-8.0.27-winx64" -D WITH_BOOST="E:\boost_1_78_0" -D MYSQLCLIENT_STATIC_BINDING=OFF -D MYSQLCLIENT_STATIC_LINKING=OFF -G "Visual Studio 16" -A "x64"
the last lines of output must to be like:
-- Configuring done
-- Generating done
-- Build files have been written to: Your-Build-Path/_BUILD
BUILDING:
launch cmd: cmake --build .\_BUILD\
There are a lot of fatal errors possible:
mysql not found
boost not found
openssl not found
openssl bad version (need 1.1.1)
no compatible options values between options
forgoten options, if this is the case, try to add the option with his default value
so check yours paths dependecies if you have errors
There somes not fatal warning:
the "is_same" test doesn't work
file sys/endiand.h not found
file sys/byteorder.h not found
when the output say "look log files output.log and errors.log" you have fatal error some where, but may be (MAY BE) don't loss time on the warnings and on the logs files... and look all the lines of the ouput, because for me the fatals errors was not listed in the logs files but in the output (may be not for you, i don't know)
INSTALLATION:
cmake --install .\_BUILD\ --config Debug
END:
in folder: E:\MYSQL\_INSTALL\lib64
there are dynamic lib
in folder: E:\MYSQL\_INSTALL\lib64\vs14
there are static lib
and E:\MYSQL\_INSTALL\lib64\vs14\mysqlcppconn.lib
will containt "get_driver_instance" functions to use mysql cpp connector etc...
if you want open mysqlcppconn.lib with 7zip, right click, open archive, open 1.txt and 2.txt, and CTRL+F your functions
NOTES:
you can't configurate in Debug (-D CMAKE_BUILD_TYPE=Release), else the first cmake cmd will create a visual studio project (E:\MYSQL\_BUILD\jdbc\connector-jdbc-deps.vcxproj) with inside a unknow linked library (MYSQLLIB-NOTFOUND-DEBUG), and the cmake build cmd will fail
in my visual studio project, i have link the two static lib, and i have copy past the two dynamic lib next to my exe, that work for me
VERSION-ARCH:
software
version
arch
windows pro
10
x64
cmake
3.22.1
x64
Microsoft Visual Studio Community 2019
16.11.8
x64
Microsoft .NET Framework
4.8.04084
x64
openssl
v1.1.1m
x64
boost
1.78.0
cross-arch ?
mysql server
8.0.27
x64
mysql cpp connector
8.0.27
x64