A. create and implement a C ++ class library
The name of this class library is swiglib. a random number is generated using a random class. First, create a shared library project in Eclipse:
Add the random class:
/*
* Random. h
*/
# IfndefRandom_h _
# DefineRandom_h _
NamespaceSwiglib {
Class
Random {
Public:
Random();
Int getint(IntMax );
Virtual ~ Random();
};
}/*NamespaceSwigtest */
# Endif/* Random_h _*/
/*
* Random. cpp
*/
# Include
"Random. H"
# Include
<Stdlib. h>
# Include
<Ctime>
NamespaceSwiglib {
Random: Random(){
Srand((Unsigned)Time(0 ));
}
Int random: getint(IntMax ){
Return
Rand() % Max;
}
Random ::~ Random(){
}
}/*NamespaceSwiglib */
B. Use swig to generate Java code
Download swigwin-x.x from http://www.swig.org/download.htmlto decompress the file.
Write an interface file that swig can recognize. This file will be read by swig and generate interface code in different languages. Create the interface file swiglib. I here:
% Module swiglib
% {
# Include "random. H"
%}
% Include "random. H"
Call the swig command line to generate the Java code and the corresponding C ++ packaging code:
D: \ Software \ develop \ swig \ swigwin-2.0.6> swig-C ++-Java-packagenet. wuyf D: \ wuyf \ workspace \ c \ swiglib \ SRC \ swiglib. I
C. compile and generate a dynamic link library
JNI must be referenced in the generated Java code. Therefore, some include directories of Java must be added to eclipse before Compilation:
Right-click the project-> properties-> C/C ++ general-> paths and symbols, add the % java_home %/include and % java_home %/include/Win32 paths to the DES in the compilation environment:
Compiling a link library that can be called by Java in Windows eclipse also requires a very important parameter configuration, right-click the project-> properties-> C/C ++ build-> Settings, modify command in mingw C ++ linker in tool settings, add-wl, -- add-stdcall-alias option (refer to http://www.swig.org/tutorial.html ):
Next, use eclipse to compile!
D. Call the Link Library in Java
First, note that in windows, mingw generates a 32-bit link library, so a 32-bit JDK is required for calling. The following describes how to copy the Java class generated by swig to the Java project. Ensure that the package names are consistent and test the call:
PackageNet. wuyf;
ImportOrg. testng. Assert;
ImportOrg. testng. Annotations. beforeclass;
ImportOrg. testng. Annotations. test;
Public classRandomtest {
PrivateRandom r =Null;
Privatestatic int Maxint= 100;
Static{
System.Load("D :\\Wuyf\ Workspace \ c \\Swiglib\ Debug \ libswiglib. dll ");
}
@ Beforeclass
Publicvoid beforeclass(){
R =NewRandom ();
}
@ Test (threadpoolsize = 1,Invocationcount= 100)
Publicvoid getint(){
IntI = R. getint (Maxint);
Assert.Asserttrue(I> = 0 & I <Maxint);
System. Out. println (I );
}
}