简体   繁体   中英

calling c++ function from Java using swig in Windows, getting java.lang.UnsatisfiedLinkError

I have this c++ code:

/* File : example.cpp */
#include <iostream>
#include <time.h>

double My_variable = 3.0;

int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}

int my_mod(int x, int y) {
return (x%y);
}

char *get_time()
{
time_t ltime;
time(&ltime);
return ctime(&ltime);
}          

and I have this .i code:

/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}

extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();

I am trying to call these functions from inside java. So in windows 7 (with mingw) cmd I do:

swig -c++ -java example.i
g++ -c example.cpp example_wrap.cxx -I "C:\Program Files (x86)\Java\jdk1.8.0_31\include" -I "C:\Program Files (x86)\Java\jdk1.8.0_31\include\win32"
g++ -shared example.o example_wrap.o -o example.dll -I "C:\Program Files (x86)\Java\jdk1.8.0_31\include" -I "C:\Program Files (x86)\Java\jdk1.8.0_31\include\win32"

This creates a dll file. Now I try to run the following java program:

public class main {
   public static void main(String argv[]) {
     System.loadLibrary("example");
     System.out.println(example.fact(5));
     System.out.println(example.get_time());
   }
 }

So I run

javac main.java

It compiles fine, but when I run using

java main

I get this error:

Exception in thread "main" java.lang.UnsatisfiedLinkError:     exampleJNI.fact(I)I
        at exampleJNI.fact(Native Method)
        at example.fact(example.java:20)
        at main.main(main.java:4)

What is the problem?

Problem solved by using

-Wl,--kill-at

Thanks for comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM