Tool Native Library Generator (C/C++ to B4A)

logo.png

Native Library Generator 4.20 (2018-11-11)
Written in B4J, this program allows you to write or import C/C++ code and have all the functions compiled into a native (.so) library, which in turn is included in a ready-to-use B4A Java lib. When using already existing code, if present, the main() function will be automatically ignored. If you're familiar with C/C++ but not with JNI or NDK, this is the right tool for you! No JAVA required.

Requirements:

Open Source:
This project is open source, under the GNU General Public License. Enjoy! :)
https://gitlab.com/brunowonder/NativeLibraryGenerator-CommunityEdition

Price (pay what you want):
If you wish to buy me a beer (or even dinner!) just follow the link below.
https://www.paypal.me/ninjadynamics
0317.png
0317.png
0317.png

How does it work:
upload_2017-10-27_15-57-1-png.61061


Video Demos:

Updates:
[Version 4.21] [2018-11-12] [CRITICAL]
QuickSource mode fixed
For background music add "nlg.mp3" to the NLG folder ;)

[Version 4.20] [2018-11-11] [NEW FEATURES]
Now supporting multiple source files
Select which files should be exposed to B4A
Requires NDK r18b (please update)
Bug fixes

[Version 4.01] [2017-05-07] [NEW FEATURES]
The 'cpu-features' library can now be used
Custom Makefiles may now be used
Custom Java wrappers may now be used
Bug fixes

[Version 4.00] [2017-05-07] [NEW FEATURES]
Complete visual overhaul
Specifying additional include paths is now possible
Specifying additional prebuilt libraries is now possible
Specifying the target ABI's is now possible
Compatible ABI's are now auto-detected if possible
Handling
multiple projects is now possible

[Version 3.0] [2017-05-07] [NEW FEATURES]
Returning arrays is now possible.
B4A logging with printf() is now possible.


[Version 2.9] [2016-08-12] [NEW FEATURES]
Small UI redesign and bug fixes.
Code clean-up.

Little bit more user-friendly.
Custom makefiles.

[Version 2.8] [2016-07-12] [NEW FEATURES]
Now supporting local #include files.
Now supporting external project locations.
New video demo.
Minor bug fixes.

[Version 2.7] [2016-03-14] [CRITICAL]
Major bug fixes.

[Version 2.6] [2016-01-31] [IMPORTANT]
Important bug fixes.
MazeSolver 1.5 Included as example source code.

[Version 2.5] [2016-01-31] [NEW FEATURES]
Now supporting comment transcription from C++ to B4A.
New splash screen.
Minor bug fixes.

[Version 2.4] [2016-01-27] [CRITICAL]
Critical bug fix regarding string (char*) support.
Cool new intro/exit screens added.


[Version 2.3] [2016-01-25] [NEW FEATURES]
Now supporting Strings (char*), both passing and returning.

[Version 2.2] [2016-01-20] [IMPORTANT]
Now supporting simple C/C++ typedef struct.
Now supporting C/C++ inline functions.

Minor bug fixes.

[Version 2.1] [
2016-01-12] [CRITICAL]
Included example (NinjaCore) source code updated. Several bug fixes.

[Version 2.1] [2016-01-12] [IMPORTANT]
Now supporting C++ headers, such as <vector> or <algorithm>.

[Version 2.0] [2016-01-10] [CRITICAL]
Major issue corrected. Please download Native Library Generator again.

Included Example:

In order to showcase this software's capabilities, I decided to include my MazeSolver project.

A. Download link:

B. Instructions (QuickSource Mode):
In QuickSouce mode all you have to do is write some code and hit the Generate Library button.

1. Before anything else, please make sure you have installed the following required software:
B4A, Simple Library Compiler and Android NDK


2. Download the .jar file into a system-writable folder (NOT Program Files).

3. Run NLG and provide the necessary software paths, as seen below.
upload_2018-11-12_11-56-16.png


4. Compile the example by clicking the big blue button.
upload_2018-11-12_11-56-37.png



5. Test the library you just compiled with this B4A project:
https://www.b4x.com/android/forum/t...orithm-w-path-optimization.61998/#post-391230

6. As you can see, it works!
upload_2018-11-12_12-14-11.png

C. LibFastMath Example code (Copy/Paste to NLG):
B4X:
//LibFastMath 1.00 - Native Library Example

//FastSin() and FastCos() by Allen Chou
//http://allenchou.net/2014/02/game-math-faster-sine-cosine-with-polynomial-curves

//FastSqrt() adapted from Quake 3's Fast Inverse Square Root algorithm
//https://en.wikipedia.org/wiki/Fast_inverse_square_root

#define PI         (3.1415926535f)
#define HALF_PI    (0.5f * PI)
#define TWO_PI     (2.0f * PI)
#define TWO_PI_INV (1.0f / TWO_PI)

float FastSin(float x);
float FastCos(float x);
float FastSqrt(float x);

inline float Hill(float x)
{
  const float a0 = 1.0f;
  const float a2 = 2.0f / PI - 12.0f / (PI * PI);
  const float a3 = 16.0f / (PI * PI * PI) - 4.0f / (PI * PI);
  const float xx = x * x;
  const float xxx = xx * x;

  return a0 + a2 * xx + a3 * xxx;
}

float FastSin(float x)
{
  // wrap x within [0, TWO_PI)
  const float a = x * TWO_PI_INV;
  x -= static_cast<int>(a) * TWO_PI;
  if (x < 0.0f)
    x += TWO_PI;

  // 4 pieces of hills
  if (x < HALF_PI)
    return Hill(HALF_PI - x);
  else if (x < PI)
    return Hill(x - HALF_PI);
  else if (x < 3.0f * HALF_PI)
    return -Hill(3.0f * HALF_PI - x);
  else
    return -Hill(x - 3.0f * HALF_PI);
}

float FastCos(float x)
{
  return FastSin(x + HALF_PI);
}

float FastSqrt(float x)
{
    //This is the method used in Quake3
    const float xhalf = 0.5f*x;

    //Get bits for floating value
    union
    {
        float x;
        int i;
    } u;
    u.x = x;

    //Give initial guess y0
    u.i = 0x5f3759df - (u.i >> 1);

    //Newton step, repeating increases accuracy
    return (x*u.x*(1.5f - xhalf*u.x*u.x));
}

D. How does it work:
Initially, I created this program in order to speed-up the process of writing JNI C/C++ code. Following B4A's RAD philosophy, it allows me to write native code in Visual Studio and compile it into a fully-working B4A lib within a single click.
E. Internal Functions:
If you wish any of your native function not to be exposed in the B4A library, you may do so by either changing their name from foo() into privateFoo() or simply adding a "::ignore" the function's comments.
B4X:
//This function will not be visible in B4A because its name starts with "private".
int privateSum(int a, int b)
{
    return a + b;
}

//This function will not be visible in B4A because this comment contains the keyword "::ignore".
int multiplication(int a, int b)
{
    return a * b;
}

//This function will be exposed in B4A.
int result(int a, int b)
{
    return privateSum(a, b) + multiplication(a, b);
}
F. Current Limitations:
As happy as I am to share this work with the B4x community, let's not forget that this is just my own internal tool, a never ending work-in-progress personal project.
Hence, it does not yet support several features such as passing Arrays into the native layer.
G. Reminder:
Please test your C/C++ code before trying to build a B4A library, as some kinds of syntax errors may crash the application.
 

Attachments

  • upload_2018-11-12_11-53-30.png
    upload_2018-11-12_11-53-30.png
    88.2 KB · Views: 422
Last edited:

sorex

Expert
Licensed User
Longtime User
Nice, wonder.

Do you have some comparison sheet handy of several routines (grid scanners, math, whatever) that shows the speed gain compared to their 'real' B4A variant?
 

wonder

Expert
Licensed User
Longtime User
So far, Informatix's maze solving algorithm seems to be faster, but due to its complexity there are still unresolved bugs/issues.
The functions provided in the included example are slightly faster, but the real performance gain comes from writing heavy/complex functions natively.
 

Stefano D'Andrea

New Member
Licensed User
Wonderful work wonder, I'm noobs in Android and B4A. I've thousand and thousand lines of C code and your tool is perfect for me.

I've tried your tool (differend configuration path for NDK and SLC) but i received the following error (slc dump)



Simple Library CompilerC:\Users\stefano\Desktop\Native Library Generator\workspace>LibraryCompiler NinjaCore C:\Users\stefano\Desktop\Native Library Generator\project
Wrong number of arguments. 2 arguments are expected (library name and project path).Simple Library CompilerC:\Users\stefano\Desktop\Native Library Generator\workspace>LibraryCompiler NinjaCore C:\Users\stefano\Desktop\Native Library Generator\project

do you have any idea ?
thanks
Stefano
 

Stefano D'Andrea

New Member
Licensed User
I've changed the name of "Native Library Generator" directory in "NativeLibraryGenerator" and i received


[08:51:59]SLC compilation FAILED.
[08:51:59] Run 'workspace\slc.bat' to see what went wrong.SLC compilation FAILED.

but the library was built and saved in
C:\Android\extras\android\support\v4

my conf is :

Name: NinjaCore
Author: Bruno Silva
Version: 1.01
[SLC] C:\Programmi\Anywhere Software\SimpleLibraryCompiler
[NDK] C:\Users\stefano\Downloads\android-ndk-r10e
[LIB] C:\Android\B4AExternalLibs
Package: com.ninjadynamics.ninjacore
 

wonder

Expert
Licensed User
Longtime User
@Stefano D'Andrea Thanks for the report. :)
I'll try to replicate your steps in order to generate the same error.

Which folder are you using to store your B4A external libs? In other words, does this [C:\Android\B4AExternalLibs] folder exist in your computer?
 
Last edited:

wonder

Expert
Licensed User
Longtime User
[08:51:59]SLC compilation FAILED.
[08:51:59] Run 'workspace\slc.bat' to see what went wrong.SLC compilation FAILED.
The SLC compilation will only (attempt) to if the NDK compile was successful.
This means that the NDK-Build was completed without problems. It's probably a configuration issue.

This folder [C:\Android\B4AExternalLibs] is the folder I use on my PC to store the B4A external libs, see screenshot.

Untitled_1.png
 
Last edited:

wonder

Expert
Licensed User
Longtime User
@Erel, Ok, I got it! :)

Provided all the correct paths, I've tried to run my program from a folder called "New Folder".
Upon compilation, SLC.bat does the following:
LibraryCompiler TestLib C:\Users\Bruno\Desktop\New Folder
Because I forgot the quotes, SLC interprets "Folder" as a 3rd argument and we get the error:
Wrong number of arguments. 2 arguments are expected (library name and project path).

This is easily solved by adding quotes:
LibraryCompiler TestLib "C:\Users\Bruno\Desktop\New Folder"

Bug corrected. Please download Native Library Generator again.
http://www.ninjadynamics.com/apps/native/native_library_generator.jar
 
Last edited:

wonder

Expert
Licensed User
Longtime User
Thank you so much!! :D

Actually, there is no title bar. It's just a colored label simulating it. ;)

B4X:
MainForm = Form1
MainForm.Title = "[C++] Native Library Generator"
MainForm.SetFormStyle("TRANSPARENT")
MainForm.Resizable = False  
MainForm.Show
MainForm.Stylesheets.Add(File.GetUri(File.DirAssets, "style.css"))
MainForm.RootPane.Style = "-fx-background-color: rgba(48, 48, 48, 1); -fx-border-color: rgba(64, 64, 64, 1);"

Dim w = MainForm.Width  As Int
Dim h = MainForm.Height As Int

fx.LoadFont(File.DirAssets, "Consolas.ttf", 12)

lblTitle.Initialize("lblTitle")
lblTitle.Style = "-fx-vertical-align: text-top; -fx-font: 12px Consolas; -fx-text-fill: rgba(0, 192, 255, 1); -fx-background-color: rgba(40, 40, 40, 1);"
lblTitle.Text = " [C++] Native Library Generator"
MainForm.RootPane.AddNode(lblTitle, 1, 1, w - 2, h * 0.05)

lblExit.Initialize("lblExit")
lblExit.Style = "-fx-vertical-align: text-top; -fx-font: 12px Consolas; -fx-text-fill: rgba(0, 192, 255, 1); -fx-background-color: rgba(40, 40, 40, 1);"
lblExit.Text = "X "
MainForm.RootPane.AddNode(lblExit, w - 20, 1, 19, h * 0.05)

lblSound.Initialize("lblSound")
lblSound.Style = "-fx-vertical-align: text-top; -fx-font: 12px Consolas; -fx-text-fill: rgba(0, 192, 255, 1); -fx-background-color: rgba(40, 40, 40, 1);"
lblSound.Text = "Snd"
MainForm.RootPane.AddNode(lblSound, w - 50, 1, 19, h * 0.05)  

txtConfgBox.Initialize("txtConfgBox")
txtConfgBox.Style = "-fx-vertical-align: text-top; -fx-font: 12px Consolas; -fx-text-fill: rgba(255, 192, 0, 1); -fx-border-color: rgba(0, 192, 255, 1); -fx-background-color: black; -fx-border-radius: 3px;"
MainForm.RootPane.AddNode(txtConfgBox, w * 0.05, h * 0.10, w * 0.50, h * 0.21)

txtStatsBox.Initialize("txtStatsBox")
txtStatsBox.Style = "-fx-vertical-align: text-top; -fx-font: 12px Consolas; -fx-text-fill: rgba(0, 192, 255, 1); -fx-border-color: rgba(0, 192, 255, 1); -fx-background-color: black; -fx-border-radius: 3px;"
txtStatsBox.Text  = ":: [C++] Native Library Generator" & CRLF & _                      
                    ":: 2015-2016 Bruno Silva / Ninja Dynamics" & CRLF & _
                    ":: Music: Kenny Chou - One Must Fall: 2097 " & CRLF & _                  
                    CRLF & CRLF & CRLF & _
                    "[" & DateTime.Time(DateTime.Now) & "] Ready." & CRLF
txtStatsBox.WrapText = True
txtStatsBox.Editable = False  
MainForm.RootPane.AddNode(txtStatsBox, w * 0.57, h * 0.10, w * 0.38, h * 0.21)

txtPasteBox.Initialize("txtPasteBox")  
txtPasteBox.Style = "-fx-vertical-align: text-top; -fx-font: 12px Consolas; -fx-text-fill: rgba(0, 255, 64, 255); -fx-border-color: rgba(0, 192, 255, 1); -fx-background-color: transparent; -fx-border-radius: 3px;"
MainForm.RootPane.AddNode(txtPasteBox, w * 0.05, h * 0.345, w * 0.90, h * 0.455)      

btnGo.Initialize("btnGo")
btnGo.Text = "Generate B4A Library"
btnGo.Style = btnGo.Style & "-fx-background-color:  rgba(0, 182, 255, 1);"
MainForm.RootPane.AddNode(btnGo, w * 0.05, h * 0.85, w * 0.90, h * 0.10)
  
bgMusic.Initialize("bgMusic", File.GetUri(File.DirAssets, "music.mp3"))
bgMusic.Volume = 0.5
bgMusic.CycleCount = -1

As you can see, I like to do everything in code, didn't use the designer a single time. :)
 
Last edited:

Stefano D'Andrea

New Member
Licensed User
The SLC compilation will only (attempt) to if the NDK compile was successful.
This means that the NDK-Build was completed without problems. It's probably a configuration issue.

This folder [C:\Android\B4AExternalLibs] is the folder I use on my PC to store the B4A external libs, see screenshot.
I would be such a coincidence to have another user using exactly the same.
I'm almost sure the error is here.

Stefano has to provide his own current (existing) B4A external libs folder, and of course has the path configured in B4A paths as well.
.....

Thank you wonder the problem is the folder [C:\Android\B4AExternalLibs]
it exists but it is not the extra lib configuration path of B4A.
thanks

p.S: The update version works fine. Thank you
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
Hello Wonder
I really like your project (because I know better and I prefer C ++ to Java), but I can not understand how it can be used in the development of applications for Android ?! Rather, what features we can develop more or better than Java \ B4A? Knowing a bit architecture of Android, so that we can access a lower level, but I do not know what we can do.
Thanks a lot
 

wonder

Expert
Licensed User
Longtime User
Hello hello!

Many thanks for your interest in my project. :)
The greatest advantage of writing native-base code is the major speed improvement over Java.
Of course, the native code always has to be well-structured by the developer, otherwise the advantages might be minimal or none at all.

A good example would be the MazeSolver library I'm currently working on.
With @Informatix's help we've done some benchmarking. The C++ version runs about 30% faster than it's Java counterpart.

Here's some practical possible implementations:
- Videogames
- Path-finding for GPS/Navigation apps
- Physics Engines
- High-Frequency Trading
- Genetic Algorithms
- Neural Networks
- Encryption Breaking Algorithms
- Scientific Research (requiring heavy math computations)
- Real-time Image Processing
- Augmented Reality
- Face recognition
- Video Processing
- Audio Processing
- Protein Folding Algorithms
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
Thank you for the explanation. I understand. Projects based on performance, that only c / C ++ can give (the king of languages). Of all could care functionality GPS / Navigation apps. I'll watch your message.
 

wonder

Expert
Licensed User
Longtime User
No problem. :)

Regarding a GPS/Nav app, the real advantage would come from having your own maps and developing your own Path Finding algorithm (turn-by-turn) navigation, at least in theory.

As a proof-of-concept, I'll try to map my neighborhood in MS-Paint, convert it into a 2-bit dot-matrix and apply my current MazeSolver lib to see if it helps me navigate the real world, in real-time. ;)
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
it would be great to have such aid to developing a good management system turns on maps. It is required, but is complex to develop.
I hope you do something about this.
thank you
 
Top